gpt4 book ai didi

c# - 无法读取现有的 excel 文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:48 25 4
gpt4 key购买 nike

下面是我读取现有 excel 文件的代码:

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
var ws = xlPackage.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;
ws.Column(4).OutlineLevel = 1;
ws.Column(4).Collapsed = true;
ws.Column(5).OutlineLevel = 1;
ws.Column(5).Collapsed = true;
ws.OutLineSummaryRight = true;
//Headers
ws.Cells["B1"].Value = "Name";
ws.Cells["C1"].Value = "Size";
ws.Cells["D1"].Value = "Created";
ws.Cells["E1"].Value = "Last modified";
ws.Cells["B1:E1"].Style.Font.Bold = true;
System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
}

当我运行代码时。它会引发运行时错误。
错误。

System.InvalidOperationException: A worksheet with this name already exists in the workbook
at OfficeOpenXml.ExcelWorksheets.Add(String Name)
at Report.Form1.ExportToExcel1(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 43

最佳答案

这也很简单:

  • 首先检查工作表是否存在,如果不存在则执行你的代码
  • 只需删除现有工作表(如果存在)并使用您的值重新添加
  • 修改现有工作表“内容”的这些值

也许可以尝试这样的事情:

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
//Check if worksheet with name "Content" exists and retrieve that instance or null if it doesn't exist
var ws = xlPackage.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Content");
//If worksheet "Content" was not found, add it
if (ws == null)
{
ws = xlPackage.Workbook.Worksheets.Add("Content");
}

//Rest of code
}

关于c# - 无法读取现有的 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14135384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com