首页 > 解决方案 > 使用 Response 类将两张工作表添加到 excel 文件中

问题描述

我有一段代码用于动态创建一个excel文件,然后用c#下载它,效果很好。这是代码:

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=filename.xls");
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

//ADD Headers
Response.Write("Name");
Response.Write("\t");
Response.Write("Age");
Response.Write("\t");
Response.Write("\n");

//ADD BODY
Response.Write("Shireen");
Response.Write("\t");
Response.Write("30");
Response.Write("\t");
Response.Write("\n");

现在的问题是如何向该文件添加第二张工作表。甚至可能吗?

标签: c#excel

解决方案


它是一个Excel文件吗?

试试看:

第 1 步:参考 Microsoft.Office.Interop.Excel(在 Visual Studio 中可用)并使用它:

using Excel = Microsoft.Office.Interop.Excel;

第 2 步:使用示例:

        private void CreateExcelFile(string sheet1Name, string sheet2Name)
        {
            Microsoft.Win32.SaveFileDialog save = new Microsoft.Win32.SaveFileDialog();
            save.Filter = "(All files)|*.*|(Excel)|*.xlsx|(Excel 97-2003)|*.xls";
            save.FilterIndex = 2;
            save.ShowDialog();
            if (save.FileName != "")
            {
                try
                {
                    // Create an Excel App
                    Excel.Application app = new Excel.Application();
                    // Create a new Workbok                
                    Excel.Workbook wb = app.Workbooks.Add(Type.Missing);
                    // Creat a new WorkSheet
                    Excel.Worksheet ws = null;
                    app.Visible = false;

                    ws = wb.ActiveSheet;

                    // Name 1
                    ws.Name = sheet1Name;

                    // WorkSheet 2
                    Excel.Worksheet ws2 = wb.Sheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);

                    // Name 2
                    ws2.Name = sheet2Name;

                    // Save
                    wb.SaveAs(save.FileName);
                    // Show the app
                    app.Visible = true;
                }

                catch (Exception ex)
                {
                    MessageBox.Show("error: " + ex.Message);
                }
            }
        }

推荐阅读