我已尝试使用以下编码在服务器端生成excel文件。
C#CODING:
public void ReadandOpenExcel(DirectoryInfo outputDir)
{
//FileInfo newFile = new FileInfo(outputDir.FullName + @"\New Microsoft Excel Worksheet.xlsx");
var ExistFile = Server.MapPath("~/excelsample.xlsx");
var File = new FileInfo(ExistFile);
using (ExcelPackage package = new ExcelPackage(File))
{
package.Load(new FileStream(ExistFile, FileMode.Open));
ExcelWorksheet workSheet = package.Workbook.Worksheets["Sheet1"];
workSheet.Cells["A8"].Value = "kevin";
package.Save();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=ProposalRequest.xslx");
**Response.BinaryWrite(package.GetAsByteArray());**
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
}
}
运行上面的代码时出现错误:" 包对象已关闭并处置,因此无法对此对象或此包的某个部分上打开的任何流执行操作。"
此行的错误:
Response.BinaryWrite(package.GetAsByteArray());
让这种编码继续前进。
提前致谢。
答案 0 :(得分:1)
如果在执行Save之前获得字节,它是否有效?
Byte[] bin = package.GetAsByteArray();
package.Save();
然后在Binarywrite中使用该值;
Response.BinaryWrite(bin);
也许它会在.Save()
来电时关闭?