c# - C# 中的 Excel - 2 张纸有问题

标签 c# excel

我使用此代码从数据集中制作 Excel:

SQL = "select Bar,Store,Serial from Counter";
            dsView = new DataSet();
            adp = new OleDbDataAdapter(SQL, Conn);
            adp.Fill(dsView, "Counter");
            adp.Dispose();
 Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
        xla.Visible = false  ; 
        Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)xla.ActiveSheet;
        int i = 1;
        foreach (DataRow comp in dsView.Tables[0].Rows)
        {
            ws.Cells[i, 1] = comp[0].ToString();
            ws.Cells[i, 2] = comp[1].ToString();
            ws.Cells[i, 3] = comp[2].ToString();
            i++;
        }

我有两个问题

如何打开新工作表以及如何关闭此过程

(我看到 Excell allwais 在后台运行)

最佳答案

How to open new sheet?



您可以使用 Workbook.Worksheets.Add 添加新工作表方法。
var newWorksheet = 
    (Worksheet)xla.Worksheets.Add(Type.Missing
                                , Type.Missing
                                , Type.Missing
                                , Type.Missing);

How to close this process?



您必须关闭工作簿并处理应用程序实例。
SQL = "select Bar,Store,Serial from Counter";
dsView = new DataSet();
using (adp = new OleDbDataAdapter(SQL, Conn)) 
    using (Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application()) {
        adp.Fill(dsView, "Counter");

        xla.Visible = false  ; 

        try {
            Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
            Worksheet ws = (Worksheet)xla.ActiveSheet;

            int i = 1;

            foreach (DataRow comp in dsView.Tables[0].Rows) {
                ws.Cells[i, 1] = comp[0].ToString();
                ws.Cells[i, 2] = comp[1].ToString();
                ws.Cells[i, 3] = comp[2].ToString();
                i++;
            }
        } finally {
            // Notice that the two following lines are totally optional as the use of 
            // using blocks assure that the used resource will necessarily be disposed
            // when getting out of the using blocks scope.
            adp.Dispose();
            xla.Dispose();
        }
}

这里有一些链接可以帮助您熟悉 Microsoft.Office.Interop.Excel COM 程序集。
  • How to: Add New Worksheets to Workbooks ;
  • Working with Worksheets ;
  • Working with Workbooks ;
  • Working with Ranges ;
  • Working with Cells .
  • 关于c# - C# 中的 Excel - 2 张纸有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4367139/

    相关文章:

    excel - 使用 VBA 将数据拆分为多个工作表

    c# - 监听一系列 UDP 端口

    excel - 从 VBA 用户定义函数返回 Excel 数组常量

    c# - 将新的 Dispatcher 绑定(bind)到 WPF 中的线程

    c# - SharpSSH 的 Scp 对象无法复制大于 2GB 的文件

    excel - 在 VBA excel 2016 64bit 中替代 Treeview

    java - 是否可以使用java和Apache POI库逐行写入excel文件

    python - ZeroMQ -> Excel RTD 服务器..有那么难吗?

    c# - 读取另一个应用程序的 Web.Config 以获取 ConnectionString

    c# - 使用 Unity 链接 C++ 头文件和 lib 文件