Open-XML-合并数据后结果文件显示错误

时间:2018-11-01 13:06:07

标签: c# .net console-application openxml openxml-sdk

通过使用OpenXML将数据从工作表复制到第一工作表,尝试将多个Excel工作表合并为单个Excel工作表。但是,当手动打开文件时,结果Excel将引发错误。通过同一程序打开时,相同的excel会显示正确的行数和数据。

代码:(输入文件有多个工作表,例如工作表,工作表1,工作表2等->将所有工作表1,工作表2的数据复制到工作表。

    public static void Main(string[] args)
    {
        DataTable dataTable = new DataTable();
        string inputFilePath = "C:\\test\\PRDTestSheet.xlsx";
        ////open the excel using openxml sdk

        using (SpreadsheetDocument doc = SpreadsheetDocument.Open(inputFilePath, true))
        {
            WorkbookPart wbPart = doc.WorkbookPart;
            Sheet mainRosterSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "TestSheet").FirstOrDefault();
            Worksheet mainWorksheet = ((WorksheetPart)wbPart.GetPartById(mainRosterSheet.Id)).Worksheet;
            SheetData mainSheetdata = (SheetData)mainWorksheet.GetFirstChild<SheetData>();

            Sheets sheetcollection = wbPart.Workbook.GetFirstChild<Sheets>();

           foreach (Sheet childSheet in sheetcollection)
            {
                 string sheetName = childSheet.Name;
                if (sheetName.StartsWith("TestSheet ("))
                {
                    Worksheet childWorksheet = ((WorksheetPart)wbPart.GetPartById(childSheet.Id)).Worksheet;
                    SheetData childsheetdata = (SheetData)childWorksheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = childsheetdata.Descendants<Row>();
                    int rowcount = rows.Count();
                    foreach (Row r in childsheetdata.Descendants<Row>())
                    {
                        Row newRow = (Row)r.Clone();
                        mainSheetdata.AppendChild(newRow);
                    }
                }

            }

            wbPart.Workbook.Save();

            IEnumerable<Row> rowsMain = mainSheetdata.Descendants<Row>();
            int rowcountMain = rowsMain.Count(); //Getting Proper row count of new sheet

            doc.Close();

        }

    }

0 个答案:

没有答案