gpt4 book ai didi

c# - 在 C# 中使用 ExcelLibrary 使用多个工作表创建多个 excel

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:40 26 4
gpt4 key购买 nike

enter image description here

我想用多个 excel 文件导出多个工作表中的数据。正如您在我的图片中看到的,我想在 ID 更改时生成工作表,当 ModalityId 更改时,我想创建新的 excel。

为了这个问题,我编写了这样的代码:

List<string> lstFile = new List<string>();
if (dtAltTag != null && dtAltTag.Rows.Count > 0)
{
string filePath = string.Empty;
string fileName = "";

Excel.Workbook workBook = new Excel.Workbook();
var workSheet = new Excel.Worksheet(fileName);

if (dtAltTag.Rows[0]["OldFormCode"] != null && dtAltTag.Rows[0]["OldFormCode"].ToString() != "")
{
fileName = dtAltTag.Rows[0]["OldFormCode"].ToString();
}
else
{
fileName = dtAltTag.Rows[0]["Code"].ToString();
}
workSheet.Name = fileName;
AddValue(0, workSheet, dtAltTag); // function is used to add the value in the sheet
workBook.Worksheets.Add(workSheet);

//data working
for (int i = 0; i < dtAltTag.Rows.Count; i++)
{
//for modality changes and first entery
//if (i == 0 || dtAltTag.Rows[i]["ModalityId"] != dtAltTag.Rows[i - 1]["ModalityId"])
//{
//if form changes then it should be in other sheet
if (i != 0 && dtAltTag.Rows[i]["ID"].ToString() != dtAltTag.Rows[i - 1]["ID"].ToString())
{
if (dtAltTag.Rows[i]["OldFormCode"] != null && dtAltTag.Rows[i]["OldFormCode"].ToString() != "")
{
fileName = dtAltTag.Rows[i]["OldFormCode"].ToString();
}
else
{
fileName = dtAltTag.Rows[i]["Code"].ToString();
}
var workSheet1 = new Excel.Worksheet(fileName);

AddValue(i, workSheet1, dtAltTag);
}
else
{

}
}

filePath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["ExcelFilesFilePath"]) + "Allitem";
if (!File.Exists(filePath))
Directory.CreateDirectory(filePath);
filePath = filePath + "\\" + fileName + "_" + DateTime.Now.ToString("MM_dd_yyy_HH_mm_ss") + ".xls";
workBook.Save(filePath);
lstFile.Add(filePath);
}
return lstFile;

当 id 更改时,我附加了新的 header ,但在那之后,我想继续导出数据,直到 id 更改无法检测到如何做到这一点?如何获取当前工作表,在其他情况下继续添加值?

我希望你已经清楚我正在尝试做什么!

提前致谢!

最佳答案

你不能这样做吗:

  • 遍历数据
  • 如果 ModalityId 不同,保存当前文件并创建一个新文件(将其分配回当前文件变量)
  • 如果 ID 不同,则创建一个新工作表(将其附加到当前文件并将其分配回当前工作表变量)
  • 将您的数据添加到当前工作表
  • 在循环外,保存当前(和最后一个)文件。

这可能是它的伪代码:

var currentFile = new ExcelFile();
var currentSheet = currentFile.AppendSheet(rows[0].SheetName);
string lastFileName;

for(int i = 0; i < rows.Count; i++)
{
// Adds new file if necessary
if(i != 0 && rows[i].ModalityId != rows[i - 1].ModalityId)
{
currentFile.Save(rows[i - 1].FileName);
currentFile = new ExcelFile();
}
// Adds new sheet if necessary
if(i != 0 && rows[i].ID != rows[i - 1].ID)
{
currentSheet = currentFile.AppendSheet(rows[i].SheetName);
}

InsertData(currentSheet, rows[i]);

lastFileName = rows[i].FileName;
}

currentFile.Save(lastFileName);

关于c# - 在 C# 中使用 ExcelLibrary 使用多个工作表创建多个 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813723/

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