我正在尝试将新工作表添加到现有工作簿中,代码运行良好,没有任何错误。但是这些更改并没有更新到excel文件中。这是我的代码
string path = "C:\TestFileSave\ABC.xlsx";
FileInfo filePath = new FileInfo(path);
if (File.Exists(path))
{
using(ExcelPackage p = new ExcelPackage())
{
using(stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
p.Load(stream);
ExcelWorksheet ws = p.Workbook.Worksheets.Add(wsName + wsNumber.ToString());
ws.Cells[1, 1].Value = wsName;
ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
ws.Cells[1, 1].Style.Font.Bold = true;
p.Save();
}
}
}
stream
对象未绑定到package
。唯一的关系是它将其在您的调用中的字节复制到Load
,然后它们是分开的。
您甚至不需要使用stream
-最好让package
自己处理它,如下所示:
var fileinfo = new FileInfo(path);
if (fileinfo.Exists)
{
using (ExcelPackage p = new ExcelPackage(fileinfo))
{
//using (stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
//p.Load(stream);
ExcelWorksheet ws = p.Workbook.Worksheets.Add(wsName + wsNumber.ToString());
ws.Cells[1, 1].Value = wsName;
ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
ws.Cells[1, 1].Style.Font.Bold = true;
p.Save();
}
}
}
这里我展示了通过在同一文件中创建一个新的工作表来将数据写入现有的excel文件。要回答您的问题:请尝试使用最后两行File.WriteAllBytes而不是p.Save().
string strfilepath = "C:\Users\m\Desktop\Employeedata.xlsx";
using (ExcelPackage p = new ExcelPackage())
{
using (FileStream stream = new FileStream(strfilepath, FileMode.Open))
{
p.Load(stream);
//deleting worksheet if already present in excel file
var wk = p.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Hola");
if (wk != null) { p.Workbook.Worksheets.Delete(wk); }
p.Workbook.Worksheets.Add("Hola");
p.Workbook.Worksheets.MoveToEnd("Hola");
ExcelWorksheet worksheet = p.Workbook.Worksheets[p.Workbook.Worksheets.Count];
worksheet.InsertRow(5, 2);
worksheet.Cells["A9"].LoadFromDataTable(dt1, true);
// Inserting values in the 5th row
worksheet.Cells["A5"].Value = "12010";
worksheet.Cells["B5"].Value = "Drill";
worksheet.Cells["C5"].Value = 20;
worksheet.Cells["D5"].Value = 8;
// Inserting values in the 6th row
worksheet.Cells["A6"].Value = "12011";
worksheet.Cells["B6"].Value = "Crowbar";
worksheet.Cells["C6"].Value = 7;
worksheet.Cells["D6"].Value = 23.48;
}
//p.Save() ;
Byte[] bin = p.GetAsByteArray();
File.WriteAllBytes(@"C:UsersmDesktopEmployeedata.xlsx", bin);
}
我最初通过使用它得到错误代码"写入操作期间发生磁盘错误。(HRESULT:0x8003001D(STG_E_WRITEFAULT)异常)",但后来了解到这是因为我要修改的现有Excel文件不完全符合MS Excel格式。我在Open office中以.xls文件的形式创建了原始excel文件,但EPPlus无法读取。当我在Online excel中重新生成此原始excel文件时,一切都很好。