如何使用 C# 从 DataSet 创建包含多个工作表的 excel 文件 [英] How to create excel file with multiple sheets from DataSet using C#

查看:19
本文介绍了如何使用 C# 从 DataSet 创建包含多个工作表的 excel 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to create excel file with multiple sheets from DataSet using C#. I have successfully created an excel file with single sheet. But I am not able to do that for multiple sheets.

问候严厉的

推荐答案

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

Here is a simple C# class that programatically creates an Excel WorkBook and adds two sheets to it, and then populates both sheets. Finally, it saves the WorkBook to a file in the application root directory so that you can inspect the results...

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 的引用(您可能已经这样做了,因为您正在创建一张工作表).

To do this, you would need to add a reference to Microsoft.Office.Interop.Excel to your project (you may have done this already since you are creating one sheet).

添加第二张工作表的语句是...

The statement that adds the second sheet is...

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

1"参数指定一个工作表,如果您想一次添加多个工作表,它可以更多.

the '1' argument specifies a single sheet, and it can be more if you want to add several sheets at once.

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

Final note: the statement oXL.Visible = false; tells Excel to start in silent mode.

这篇关于如何使用 C# 从 DataSet 创建包含多个工作表的 excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆