简体   繁体   English

使用 C# 中的 ExcelLibrary 创建具有多个工作表的多个 Excel

[英]create multiple excels with multiple sheet using ExcelLibrary in C#

在此处输入图像描述

I want to export the data in multiple sheets with multiple excel files.我想用多个 excel 文件将数据导出到多个工作表中。 As you can see in my image I want to generate sheets as ID changes and when ModalityId changes I want to create new excel.正如您在我的图像中看到的,我想在ID更改时生成工作表,当ModalityId更改时,我想创建新的 excel。

I have made code like this for this concern:为此,我编写了这样的代码:

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;

When the id is changed I append new header but after that, I want to continue export data till the id change can't detect how to do this?当 id 更改时,我 append new header 但之后,我想继续导出数据,直到 id 更改无法检测到如何执行此操作? How can I get the current sheet where I continue adding the value in else case?在其他情况下,如何获取我继续添加值的当前工作表?

I hope you are cleared of what I am trying to do!我希望你清楚我想要做什么!

Thanks in advance!提前致谢!

Can't you do it otherwise:你不能这样做吗:

  • loop through data循环数据
  • if ModalityId is different save current file and create a new one (assign it back to current file variable)如果ModalityId不同,则保存当前文件并创建一个新文件(将其分配回当前文件变量)
  • if ID is different create a new sheet (append it to current file and assign it back to current sheet variable)如果ID不同,则创建一个新工作表(将其附加到当前文件并将其分配回当前工作表变量)
  • add your data to current sheet将您的数据添加到当前工作表
  • outside the loop, save the current (and last) file.在循环之外,保存当前(和最后一个)文件。

That could be pseudo-code for it:这可能是它的伪代码

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);

With the reference of 'Rafalon' code, I made some change in my code and its working fine !参考“Rafalon”代码,我对代码进行了一些更改,并且运行良好! thank You!谢谢你!

My code is as below:我的代码如下:

 var filePath = "";
            string 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();
            }

            int Row = 0;
            var currentFile = new Excel.Workbook();
            var currentSheet = new Excel.Worksheet(fileName);
            currentFile.Worksheets.Add(currentSheet);

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


                for (int i = 0; i < dtAltTag.Rows.Count; i++)
                {

                    if (i == 0)
                    {
                        AddValue(i, currentSheet, dtAltTag, Row);
                    }
                    else
                    {
                        if (dtAltTag.Rows[i]["ModalityId"].ToString() != dtAltTag.Rows[i - 1]["ModalityId"].ToString())
                        {
                            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";
                            lstFile.Add(filePath);
                            currentFile.Save(filePath);
                            currentFile = new Excel.Workbook();

                        }
                        if (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();
                            }
                            currentSheet = new Excel.Worksheet(fileName);
                            currentFile.Worksheets.Add(currentSheet);
                            Row = 0;

                        }

                        AddValue(i, currentSheet, dtAltTag, Row);


                    }
                    Row++;

                }


                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";           
                currentFile.Save(filePath);
                lstFile.Add(filePath);

            }

This function of adding value in sheet is might be useful:这个 function 在工作表中增加价值可能有用:

private void AddValue(int i, Excel.Worksheet workSheet, DataTable dtAltTag, int Row)
        {
            //Header Working starts here
            string[] columName = new string[] { "column1", "column2", "column2", "column2", "column2" }; //add header as per you requirement
            if (Row == 0)
            {
                for (int c = 0; c < columName.Length; c++)
                {
                    workSheet.Cells[0, c] = new Excel.Cell(columName[c]);
                }
            }

            //add data
            for (int c = 0; c < columName.Length; c++)
            {
                workSheet.Cells[Row + 1, c] = new Excel.Cell(dtAltTag.Rows[i].ItemArray[c].ToString());            
            }


        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM