我正在使用tempalte excel表创建一个excel表。
我有一个代码
try
{
FileInfo newFile = new FileInfo(@"D:\ExcelFromTemplate.xlsx");
FileInfo template = new FileInfo(@"D:\template.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile,template))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets["Sheet1"];
ExcelCell cell = worksheet.Cell(5,1);
cell.Value = "15";
//worksheet.Cell(5, 1).Value = "Soap";
//xlPackage.Save();
Response.Write("Excel file created successfully");
}
}
catch (Exception ex)
{
Response.WriteFile(ex.InnerException.ToString());
}
此代码创建与模板excel文件相同的新excel文件,但无法添加单元格值。为什么?
我曾尝试过两种方法,如上面的单元格代码(5,1)。但excel表创建时不会写入单元格值。我们如何添加它。
此致 吉里什
答案 0 :(得分:3)
您需要保存文件以保留所做的更改。使用save()
try
{
FileInfo newFile = new FileInfo(@"D:\ExcelFromTemplate.xlsx");
FileInfo template = new FileInfo(@"C:\Example.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile , template))
{
//Added This part
foreach (ExcelWorksheet aworksheet in xlPackage.Workbook.Worksheets)
{
aworksheet.Cell(1, 1).Value = aworksheet.Cell(1, 1).Value;
}
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets["My Data"];
ExcelCell cell = worksheet.Cell(5, 1);
cell.Value = "15";
//worksheet.Cell(5, 1).Value = "Soap";
xlPackage.Save( );
//Response.Write("Excel file created successfully");
}
}
catch (Exception ex)
{
//Response.WriteFile(ex.InnerException.ToString());
}
遇到了问题。这个问题是ExcelPackage固有的。 同样,您必须打开每个工作表并对其进行一些更改才能保存。
在论坛中搜索更多解释。