写入Excel:无法使用EPPLUS访问封闭的stream

我环顾四周,大多数情况下我看到比我自己更复杂的问题的例子。

所以,我build议使用EPPLUS而不是EXCEL INTEROP,因为性能有所提高。 这是我第一次使用它,也是第一次遇到内存stream,所以我不确定这里有什么问题。 我正在尝试写入Excel文件并将该Excel文件转换为PDF。 为此,我通过NUGET安装了以下内容:

  1. EPPLUS
  2. EPPLUSExcel

这是我的代码:

if (DGVmain.RowCount > 0) { //Source OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Excel Files|*.xls;*.xlsx"; openFileDialog.ShowDialog(); lblSuccess.Text = openFileDialog.FileName; lblPathings = Path.ChangeExtension(openFileDialog.FileName, null); int count = DGVmain.RowCount; int current = 0; int ballast = 0; 

对于DataGridView中的每一行,执行写入Excel,然后转换为PDF。

  foreach (DataGridViewRow row in DGVmain.Rows) { //Drag if (lblSuccess.Text == null) return; string drags = Convert.ToString(row.Cells[0].Value); string dragsy = Convert.ToString(row.Cells[1].Value); Persona = drag; generateID(); //Initialize the Excel File try { 

这里是我期望的东西是错的地方:

  using (ExcelPackage p = new ExcelPackage()) { using (FileStream stream = new FileStream(lblSuccess.Text, FileMode.Open)) { ballast++; lblItem.Text = "Item #" + ballast; p.Load(stream); ExcelWorkbook WB = p.Workbook; if (WB != null) { if (WB.Worksheets.Count > 0) { ExcelWorksheet WS = WB.Worksheets.First(); WS.Cells[82, 12].Value = drag13; WS.Cells[84, 12].Value = ""; WS.Cells[86, 12].Value = 0; //========================== Form WS.Cells[95, 5].Value = drag26; WS.Cells[95, 15].Value = drag27; WS.Cells[95, 24].Value = drag28; WS.Cells[95, 33].Value = drag29; //========================== Right-Seid WS.Cells[14, 31].Value = drag27; WS.Cells[17, 31].Value = drag27; } } Byte[] bin = p.GetAsByteArray(); File.WriteAllBytes(lblPathings, bin); } p.Save(); } } catch (Exception ex) { MessageBox.Show("Write Excel: " + ex.Message); } 

使用EPPLUSEXCEL和SpireXLS将单独的方法转换为PDF。

  finally { ConvertToPdf(lblSuccess.Text, finalformat); } } } 

除了标题中提到的错误,编译器不会抛出任何错误。

您已经在这里保存了ExcelPackage

 Byte[] bin = p.GetAsByteArray(); 

所以当你以后再尝试保存时,

 p.Save(); 

ExcelPackage已经closures。 即删除你的代码中的Save()调用,你很好。