C# WinForm导出Excel方法介绍

时间:2022-12-01 13:25:57 

.NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢;如下代码所示已经做了优化,将一个二维对象数组赋值到一个单元格区域中(下面的代码中只能用于导出列数不多于26列的数据导出):

Office PIA


public static void ExportToExcel(DataSet dataSet, string outputPath)
{
    Excel.ApplicationClass excel = new Excel.ApplicationClass();
    Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
    int sheetIndex = 0;
    foreach (System.Data.DataTable dt in dataSet.Tables)
    {
        object[,] data = new object[dt.Rows.Count + 1, dt.Columns.Count];
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            data[0, j] = dt.Columns[j].ColumnName;
        }
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data[i + 1, j] = dt.Rows[i][j];
            }
        }
        string finalColLetter = string.Empty;

        string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int colCharsetLen = colCharset.Length;
        if (dt.Columns.Count > colCharsetLen)
        {
            finalColLetter = colCharset.Substring(
                (dt.Columns.Count - 1) / colCharsetLen - 1, 1);
        }
        finalColLetter += colCharset.Substring(
                (dt.Columns.Count - 1) % colCharsetLen, 1);

        Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets.Add(
            workbook.Sheets.get_Item(++sheetIndex),
            Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
        sheet.Name = dt.TableName;
        string range = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
        sheet.get_Range(range, Type.Missing).Value2 = data;
        ((Excel.Range)sheet.Rows[1, Type.Missing]).Font.Bold = true;
    }
    workbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    workbook.Close(true, Type.Missing, Type.Missing);
    workbook = null;
    excel.Quit();
    KillSpecialExcel(excel);
    excel = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);

static void KillSpecialExcel(Excel.Application app)
{
    try
    {
        if (app != null)
        {
            int processId;
            GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId);
            System.Diagnostics.Process.GetProcessById(processId).Kill();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

文件流

这种方法的效率明显高于第一种,而且也不需要安装Office,但是导出的xls文件并不符合Excel的格式标准,在打开生成的xls文件时会提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.


public static void ExportToExcel(System.Data.DataSet ds, string path)
{
    StreamWriter sw = null;
    try
    {
        long totalCount = ds.Tables[0].Rows.Count;
        sw = new StreamWriter(path, false, Encoding.Unicode);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        {
            sb.Append(ds.Tables[0].Columns[i].ColumnName + "\t");
        }
        sb.Append(Environment.NewLine);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                sb.Append(ds.Tables[0].Rows[i][j].ToString() + "\t");
            }
            sb.Append(Environment.NewLine);
        }
        sw.Write(sb.ToString());
        sw.Flush();
    }
    catch (IOException ioe)
    {
        throw ioe;
    }
    finally
    {
        if (sw != null)
        {
            sw.Close();
        }
    }
}

标签:C#,WinForm,导出Excel
0
投稿

猜你喜欢

  • maven打包如何指定jdk的版本

    2022-12-21 20:59:20
  • Android开发Jetpack组件WorkManager用例详解

    2023-05-09 03:27:07
  • spring boot使用sharding jdbc的配置方式

    2022-02-16 00:29:15
  • Java实现三子棋小游戏

    2022-09-12 01:27:20
  • Java中使用StackWalker和Stream API进行堆栈遍历

    2023-04-12 11:29:07
  • 混合语言编程—C#使用原生的Directx和OpenGL绘图的方法

    2022-06-18 14:36:41
  • springboot结合maven配置不同环境的profile方式

    2022-05-28 12:00:16
  • Springboot 全局时间格式化操作

    2022-08-17 03:23:51
  • Java spring的三种注入方式详解流程

    2021-07-02 12:25:47
  • Java实现经典游戏打砖块游戏的示例代码

    2021-06-25 13:30:16
  • Java输入输出流的使用详细介绍

    2023-08-01 22:21:22
  • Java JVM字节码指令集总结整理与介绍

    2021-09-18 17:10:20
  • 关于MyBatis模糊查询的几种实现方式

    2023-05-09 04:23:12
  • Android 管理Activity中的fragments

    2022-06-30 16:41:37
  • android阅读器长按选择文字功能实现代码

    2023-09-16 08:48:42
  • Android开发中ImageLoder加载网络图片时将图片设置为ImageView背景的方法

    2021-12-14 14:58:38
  • Java对象传递与返回的细节问题详析

    2023-04-07 16:42:50
  • c# 三种方法调用WebService接口

    2021-08-05 16:49:38
  • unity实现贪吃蛇游戏

    2022-05-28 07:07:51
  • C++判断pe文件实例

    2022-01-19 12:29:52
  • asp之家 软件编程 m.aspxhome.com