该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:\Users\m\Desktop\Employeedata.xlsx", bin); }