gpt4 book ai didi

c# - 将excel工作簿转换为内存流/字节数组以下载

转载 作者:行者123 更新时间:2023-12-04 20:30:52 25 4
gpt4 key购买 nike

我创建了一个 Excel 工作簿。我可以将此 Excel 工作簿直接转换为内存流或字节数组以通过 HTTP 传递吗?我不想保存 Excel 工作簿。我需要通过 Angular js 下载这个 excel 文件。我正在使用 Web API 2

    using Excel = Microsoft.Office.Interop.Excel;
private MemoryStream ExportDataSetToExcel()
{
System.Data.DataTable employeeTable = new System.Data.DataTable("Employee");
employeeTable.Columns.Add("Employee ID");
employeeTable.Columns.Add("Employee Name");
employeeTable.Rows.Add("1", "ABC");
employeeTable.Rows.Add("2", "DEF");
employeeTable.Rows.Add("3", "PQR");
employeeTable.Rows.Add("4", "XYZ");

////Create a Department Table
System.Data.DataTable departmentTable = new System.Data.DataTable("Department");
departmentTable.Columns.Add("Department ID");
departmentTable.Columns.Add("Department Name");
departmentTable.Rows.Add("1", "IT");
departmentTable.Rows.Add("2", "HR");
departmentTable.Rows.Add("3", "Finance");

////Create a DataSet with the existing DataTables
DataSet ds = new DataSet("Organization");
ds.Tables.Add(employeeTable);
ds.Tables.Add(departmentTable);

////Creae an Excel application instance
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();

foreach (System.Data.DataTable table in ds.Tables)
{
////Add a new worksheet to workbook with the Datatable name
Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
excelWorkSheet.Name = table.TableName;

for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
excelWorkSheet.Cells[1, i].Font.Bold = true;
}

for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
excelWorkSheet.Cells[j + 2, k + 1].Interior.Color = Excel.XlRgbColor.rgbRed;
}
}
}

MemoryStream ms = new MemoryStream();

////excelWorkBook.SaveAs(ms, Type.Missing, Type.Missing, Type.Missing, true, false, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
excelWorkBook.Close();
excelApp.Quit();
return ms;
}

最佳答案

不能直接转换。您必须将文件保存到临时路径

public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
string path = Path.GetTempFileName();
try
{
app.ActiveWorkbook.SaveCopyAs(path);
return File.ReadAllBytes(path);
}
finally
{
if(File.Exists(path))
File.Delete(path);
}
}

关于c# - 将excel工作簿转换为内存流/字节数组以下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com