使用C#创建Excel表的最简单方法是什么?

Rex*_*exE 9 c# excel

我有一些表格数据,我想把它变成Excel表格.

可用软件:

  • .NET 4(C#)
  • Excel 2010(使用Excel API即可)
  • 我不想使用任何第三方库

有关数据的信息:

  • 几百万行
  • 5列,所有字符串(非常简单和常规的表结构)
  • 在我的脚本中,我目前正在使用嵌套的List数据结构,但我可以更改它
  • 脚本的性能并不重要

在线搜索给出了很多结果,我很困惑我是否应该使用OleDb,ADO RecordSets或其他东西.其中一些技术对于我的场景来说似乎有些过分,有些看起来可能已经过时了.

最简单的方法是什么?

编辑:这是我打算从我参加的桌面运行的一次性脚本.

Tyl*_*eat 8

避免不惜一切代价使用COM互操作.使用第三方API.真.事实上,如果你正在做这个服务器端,你几乎必须这样做.有很多免费选择.我强烈建议使用EPPlus,但也有企业级解决方案.我已经使用了相当数量的EPPlus,效果很好.与interop不同,它允许您生成Excel文件而无需在计算机上安装Excel,这意味着您也不必担心COM对象作为后台进程而存在.即使使用适当的对象处理,Excel进程也不会总是结束.

http://epplus.codeplex.com/releases/view/42439

我知道你说你想避开第三方图书馆,但他们真的是要走的路.Microsoft不建议自动化Office.无论如何,这并不意味着自动化.

http://support.microsoft.com/kb/257757

但是,您可能需要重新考虑将"几百万行"插入到单个电子表格中.


Rap*_*Rap 6

尊重您的请求,以避免第三方工具和使用COM对象,这是我如何做到这一点.

  1. 添加对项目的引用:Com对象Microsoft Excel 11.0.
  2. 模块顶部添加:

    using Microsoft.Office.Interop.Excel;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 像这样添加事件逻辑:

    private void DoThatExcelThing()
    {
    
        ApplicationClass myExcel;
        try
        {
            myExcel = GetObject(,"Excel.Application")
        }
        catch (Exception ex)
        {
            myExcel = New ApplicationClass()
        }
    
        myExcel.Visible = true;
        Workbook wb1 = myExcel.Workbooks.Add("");
        Worksheet ws1 = (Worksheet)wb1.Worksheets[1];
    
        //Read the connection string from App.Config
        string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["NewConnString"].ConnectionString;
    
        //Open a connection to the database
        SqlConnection myConn = new SqlConnection();
        myConn.ConnectionString = strConn;
        myConn.Open();
    
        //Establish the query
        SqlCommand myCmd = new SqlCommand("select * from employees", myConn);
        SqlDataReader myRdr = myCmd.ExecuteReader();
    
        //Read the data and put into the spreadsheet.
        int j = 3;
        while (myRdr.Read())
        {
            for (int i=0 ; i < myRdr.FieldCount; i++)
            {
                ws1.Cells[j, i+1] = myRdr[i].ToString();
            }
            j++;
        }
    
        //Populate the column names
        for (int i = 0; i < myRdr.FieldCount ; i++)
        {
            ws1.Cells[2, i+1] = myRdr.GetName(i);
        }
        myRdr.Close();
        myConn.Close();
    
        //Add some formatting
        Range rng1 = ws1.get_Range("A1", "H1");
        rng1.Font.Bold = true;
        rng1.Font.ColorIndex = 3;
        rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;
    
        Range rng2 = ws1.get_Range("A2", "H50");
        rng2.WrapText = false;
        rng2.EntireColumn.AutoFit();
    
        //Add a header row
        ws1.get_Range("A1", "H1").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
        ws1.Cells[1, 1] = "Employee Contact List";
        Range rng3 = ws1.get_Range("A1", "H1");
        rng3.Merge(Missing.Value);
        rng3.Font.Size = 16;
        rng3.Font.ColorIndex = 3;
        rng3.Font.Underline = true;
        rng3.Font.Bold = true;
        rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;
    
        //Save and close
        string strFileName = String.Format("Employees{0}.xlsx", DateTime.Now.ToString("HHmmss"));
        System.IO.File.Delete(strFileName);
        wb1.SaveAs(strFileName, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            XlSaveAsAccessMode.xlExclusive, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value);
        myExcel.Quit();
    
    }
    
    Run Code Online (Sandbox Code Playgroud)