c# - 使用 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");
现在的问题是如何向该文件添加第二张工作表。甚至可能吗?
解决方案
它是一个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);
}
}
}
推荐阅读
- python - Python:tbird2claws.py 问题
- laravel - 如何通过表检索信息?
- android - android.support.v7.widget.RecyclerView 作为根视图
- python-3.x - 为多类 ML 分类模型选择信息量最大的分类特征
- angularjs - ng-class not working in one situation. What are some possible cause of this?
- f# - My F# code cannot read XML using XSD template
- html - 如何在文本覆盖扩展时扩展图像?
- oracle - 当我尝试运行我编写的 Oracle 存储过程时,出现 ORA-00933:SQL 命令未正确结束错误
- c# - MVVM 应用程序中用户配置数据的实用管理
- javascript - JS - 给定对象数组,我可以返回一个仅包含选定属性的数组吗?