如何使用C#从DataSet创建包含多个工作表的Excel文件

时间:2011-11-16 18:16:43

标签: excel c#-4.0 dataset

如何使用C#从DataSet创建包含多个工作表的Excel文件。我已经用单张成功创建了一个excel文件。但我无法为多张床单做到这一点。

此致 苛刻

2 个答案:

答案 0 :(得分:16)

这是一个简单的C#类,它以编程方式创建Excel WorkBook并向其中添加两个工作表,然后填充两个工作表。最后,它将WorkBook保存到应用程序根目录中的文件中,以便您可以检查结果......

public class Tyburn1
{
    object missing = Type.Missing;
    public Tyburn1()
    {
        Excel.Application oXL = new Excel.Application();
        oXL.Visible = false;
        Excel.Workbook oWB = oXL.Workbooks.Add(missing);
        Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
        oSheet.Name = "The first sheet";
        oSheet.Cells[1, 1] = "Something";
        Excel.Worksheet oSheet2 = oWB.Sheets.Add(missing, missing, 1, missing) 
                        as Excel.Worksheet;
        oSheet2.Name = "The second sheet";
        oSheet2.Cells[1, 1] = "Something completely different";
        string fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)        
                                + "\\SoSample.xlsx";
        oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
            missing, missing, missing, missing,
            Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);
        oWB.Close(missing, missing, missing);
        oXL.UserControl = true;
        oXL.Quit();
    }
}

要执行此操作,您需要向项目添加对Microsoft.Office.Interop.Excel的引用(您可能已经创建了这个,因为您创建了一个工作表)。

添加第二张表的声明是......

Excel.Worksheet oSheet2 = oWB.Sheets.Add(missing, missing, 1, missing) 
                            as Excel.Worksheet;

'1'参数指定单个工作表,如果要一次添加多个工作表,则可以更多。

最后说明:声明oXL.Visible = false;告诉Excel以静默模式启动。

答案 1 :(得分:0)

var groupedSheetList = UserData
    .GroupBy (u => u.date)
    .Select (grp => grp.ToList ())
    .ToList ();

您可以尝试

using (var package = new ExcelPackage ()) 
    {
        foreach (var item in groupedSheetList) {
            var workSheet = package.Workbook.Worksheets.Add (item[0].date);
    }
}