• 使用Microsoft.Office.Interop.Excel和SteamWriter的方式导出Excel


    之前在另外一篇博文里面介绍了使用NPOI的方式导入导出Excel

    其实asp.net提供了相应的dll给我们操作Excel

    1.引用Microsoft.Office.Interop.Excel.dll

    通过这个dll也是可以导出Excel的,不过这种方式写起来很麻烦,代码参考如下

    /// <summary>
            /// 使用Microsoft.Office.Interop.Excel导出
            /// </summary>
            /// <param name="dt"></param>
            public static void DataTableToExcel(DataTable dt)
            {
                if (dt == null) return;
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null)
                {
                    MessageBox.Show("无法创建Excel对象,可能您的电脑未安装Excel");
                    return;
                }
    
                System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
                saveDia.Filter = "Excel|*.xlsx";
                saveDia.Title = "导出为Excel文件";
                saveDia.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
    
                if (saveDia.ShowDialog() == System.Windows.Forms.DialogResult.OK && !string.Empty.Equals(saveDia.FileName))
                {
                    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
                    Microsoft.Office.Interop.Excel.Range range = null;
                    long totalCount = dt.Rows.Count;
                    long rowRead = 0;
                    float percent = 0;
                    string fileName = saveDia.FileName;
    
                    //写入标题
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
                        range.Font.Bold = true;//粗体
                        range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
                        //加边框
                        range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
                    }
    
                    //写入内容
                    for (int r = 0; r < dt.DefaultView.Count; r++)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            worksheet.Cells[r + 2, i + 1] = dt.DefaultView[r][i];
                            range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2, i + 1];
                            range.Font.Size = 9;//字体大小
                            //加边框
                            range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
                            range.EntireColumn.AutoFit();//自动调整列宽
                        }
    
                        rowRead++;
                        percent = ((float)(100 * rowRead)) / totalCount;
                        System.Windows.Forms.Application.DoEvents();
                    }
    
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
                    if (dt.Columns.Count > 1)
                    {
                        range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
                    }
    
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(fileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出文件时出错,文件可能正被打开!
    " + ex.Message);
                        return;
                    }
    
                    workbooks.Close();
                    if (xlApp != null)
                    {
                        xlApp.Workbooks.Close();
                        xlApp.Quit();
                        int generation = System.GC.GetGeneration(xlApp);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                        xlApp = null;
                        System.GC.Collect(generation);
                    }
    
                    GC.Collect();//强行销毁
    
                    #region 强行杀死最近打开的Excel进程
    
                    System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                    System.DateTime startTime = new DateTime();
                    int m, killId = 0;
                    for (m = 0; m < excelProc.Length; m++)
                    {
                        if (startTime < excelProc[m].StartTime)
                        {
                            startTime = excelProc[m].StartTime;
                            killId = m;
                        }
                    }
                    if (excelProc[killId].HasExited == false)
                    {
                        excelProc[killId].Kill();
                    }
    
                    #endregion
                }
            }
    View Code

    2.直接把内容通过SteamWriter字节流写入到Excel

    这种方式我在本地测试是支持xls的,但是xlsx方式会打不开文件,代码参考如下

            /// <summary>
            /// 使用SteamWriter导出
            /// </summary>
            /// <param name="dt"></param>
            /// <param name="path"></param>
            public static void ExportDataTableToExcel(DataTable dt, string path)
            {
                KillSpecialExcel();
                try
                {
                    // 实例化流对象,以特定的编码向流中写入字符。  
                    StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);
                    StringBuilder sb = new StringBuilder();
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        // 添加列名称  
                        sb.Append(dt.Columns[k].ColumnName.ToString() + "	");
                    }
                    sb.Append(Environment.NewLine);
                    // 添加行数据  
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow row = dt.Rows[i];
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            // 根据列数追加行数据  
                            sb.Append(row[j].ToString() + "	");
                        }
                        sb.Append(Environment.NewLine);
                    }
                    sw.Write(sb.ToString());
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    dt.Dispose();
                }
            }
    
            /// <summary>  
            /// 结束进程  
            /// </summary>  
            private static void KillSpecialExcel()
            {
                foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                {
                    if (!theProc.HasExited)
                    {
                        bool b = theProc.CloseMainWindow();
                        if (b == false)
                        {
                            theProc.Kill();
                        }
                        theProc.Close();
                    }
                }
            }    
    View Code

    以上两种方式都可以,但是都不建议使用,通过NPOI这种第三方插件是最快的,也最方便

  • 相关阅读:
    hp一體機cartridge error及carriage jam4/22
    指纹仪zkonline.ocx:access violation...4/13
    IIS6:Service Unaviable 9/27
    寶寶的成長腳印3/15
    vs2003不能调试4/8
    C++ 的复制构造函数
    导入与导出数据 大容量复制程序(bcp)
    关于SQlserver数据库的加密应用
    DataGridView使用技巧
    使用C# 向记事本窗口发送消息
  • 原文地址:https://www.cnblogs.com/zfylzl/p/6951267.html
Copyright © 2020-2023  润新知