Added union of several excels to one file

This commit is contained in:
KharchenkoVV 2021-09-15 17:48:34 +05:00
parent 643c04be30
commit d45dc54230

View File

@ -4,6 +4,7 @@ using DocumentFormat.OpenXml.Spreadsheet;
//using AsbSaubReport;
//using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
@ -19,57 +20,62 @@ namespace ConsoleApp1
static void Main(/*string[] args*/)
{
const string firstExcelPath = @"D:\excels\excel1.xlsx";
const string secondExcelPath = @"D:\excels\excel2.xlsx";
var sourceExcelPaths = new List<string>
{
@"D:\excels\excel1.xlsx",
@"D:\excels\excel2.xlsx"
};
const string resultExcelPath = @"D:\excels\result.xlsx";
using var firstExcel = SpreadsheetDocument.Open(firstExcelPath, true);
using var secondExcel = SpreadsheetDocument.Open(secondExcelPath, true);
using (var resultExcel = SpreadsheetDocument.Create(resultExcelPath,
SpreadsheetDocumentType.Workbook, true))
// result file create and init
using (var resultExcelFile = SpreadsheetDocument.Create(resultExcelPath,
SpreadsheetDocumentType.Workbook, true))
{
var workbookPart = resultExcel.AddWorkbookPart();
var workbookPart = resultExcelFile.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
workbookPart.Workbook.AppendChild(new Sheets());
var sharedStringTablePart = resultExcel.WorkbookPart.
AddNewPart<SharedStringTablePart>();
resultExcelFile.WorkbookPart.AddNewPart<SharedStringTablePart>();
var stylesPart = resultExcel.WorkbookPart.
AddNewPart<WorkbookStylesPart>();
resultExcelFile.WorkbookPart.AddNewPart<WorkbookStylesPart>();
workbookPart.Workbook.Save();
}
using (var resultExcel = SpreadsheetDocument.Open(resultExcelPath, true))
foreach (var sourceExcelPath in sourceExcelPaths)
{
foreach (var sheet in firstExcel.WorkbookPart.Workbook.Descendants<Sheet>())
using var sourceExcelFile = SpreadsheetDocument.Open(sourceExcelPath, false);
using var resultExcelFile = SpreadsheetDocument.Open(resultExcelPath, true);
foreach (var sheet in sourceExcelFile.WorkbookPart.Workbook.Descendants<Sheet>())
{
// Чтобы писать на новый лист, нужен новый WorkSheetPart, WorkSheet, SheetData и Sheet.
// https://stackoverflow.com/questions/9120544/openxml-multiple-sheets
var resultExcelWorkSheetPart = resultExcel.WorkbookPart.AddNewPart<WorksheetPart>();
var resultExcelWorkSheetPart = resultExcelFile.WorkbookPart.AddNewPart<WorksheetPart>();
resultExcelWorkSheetPart.Worksheet = new Worksheet();
var resultExcelSheetData = resultExcelWorkSheetPart.
Worksheet.AppendChild(new SheetData());
var newSheet = new Sheet() {
Id = resultExcel.WorkbookPart.GetIdOfPart(resultExcelWorkSheetPart),
var newSheet = new Sheet()
{
Id = resultExcelFile.WorkbookPart.GetIdOfPart(resultExcelWorkSheetPart),
SheetId = sheet.SheetId.Value,
Name = sheet.Name
};
resultExcel.WorkbookPart.Workbook.Sheets.Append(newSheet);
var firstExcelWorkSheetPart = firstExcel.WorkbookPart.
resultExcelFile.WorkbookPart.Workbook.Sheets.Append(newSheet);
var sourceWorkSheetPart = sourceExcelFile.WorkbookPart.
GetPartById(sheet.Id) as WorksheetPart;
// Не самая лучшая выборка рядов текущей страницы исходного файла.
// Наверняка для этого есть метод.
var firstExcelRows = firstExcelWorkSheetPart.Worksheet.ChildElements
var sourceFileCurrentListRows = sourceWorkSheetPart.Worksheet.ChildElements
.FirstOrDefault(w => w.LocalName == "sheetData").ChildElements;
// Числовые ячейки хранятся как есть и переносятся без проблем, а вот значения строковых ячеек хранятся
@ -79,27 +85,28 @@ namespace ConsoleApp1
// Разные всяческие Part'ы можно найти тут:
// https://docs.microsoft.com/ru-ru/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart?view=openxml-2.8.1
var firstExcelStringTable = firstExcel.WorkbookPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault().SharedStringTable;
resultExcel.WorkbookPart.SharedStringTablePart.SharedStringTable =
var firstExcelStringTable = sourceExcelFile.WorkbookPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault().SharedStringTable;
resultExcelFile.WorkbookPart.SharedStringTablePart.SharedStringTable =
firstExcelStringTable.CloneNode(true) as SharedStringTable;
// Аналогично переносим таблицу стилей ячеек (жирный шрифт и прочее).
// Иначе ячейки переносятся абсолютно обычными, без всякой стилизации.
var stylesSheet = firstExcel.WorkbookPart.GetPartsOfType<WorkbookStylesPart>()
.FirstOrDefault().Stylesheet;
resultExcel.WorkbookPart.WorkbookStylesPart.Stylesheet =
var stylesSheet = sourceExcelFile.WorkbookPart.GetPartsOfType<WorkbookStylesPart>()
.FirstOrDefault().Stylesheet;
resultExcelFile.WorkbookPart.WorkbookStylesPart.Stylesheet =
stylesSheet.CloneNode(true) as Stylesheet;
// Клонируем ряды в новый файл (без клонирования они не вытаскиваются из общего дерева)
foreach (var row in firstExcelRows)
foreach (var row in sourceFileCurrentListRows)
resultExcelSheetData.AppendChild(row.CloneNode(true));
}
}
Console.WriteLine("Done. Press any key to quit.");
Console.ReadKey();
}