我想合并单元格是excel。通过使用DOM方法,我可以轻松完成。但是由于我的excel文件太大,当我试图获取工作表时,它会抛出内存不足异常。所以我必须使用SAX方法来读取excel文件。但我不知道如何在这种方法中合并细胞。 搜索了很多,但每个人都提供了DOM方法的解决方案。
任何人都可以提供帮助,在此先感谢。
答案 0 :(得分:0)
您可以使用EPPlus执行此操作:
using (ExcelPackage package = new ExcelPackage(new FileInfo(@"C:\Temp\example.xlsx")))
{
ExcelWorksheet ws = package.Workbook.Worksheets.First();
ws.Cells["A1:A2"].Merge = true;
package.Save();
}
答案 1 :(得分:0)
我的解决方案是:通过openxmlreader从旧工作表中读取全部数据,而不是通过openxmlwriter写入新工作表中,因此我可以在将数据写入sheetdata元素后添加合并单元格元素。
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(YourExcelfileName, true))
{
// Create reference of main Workbook part, which contains all reference.
WorkbookPart objworkbook = myDoc.WorkbookPart;
// pick up first worksheet
WorksheetPart objworksheet = objworkbook.WorksheetParts.First();
// will be used in end while creating sheet data
string objorigninalSheetId = objworkbook.GetIdOfPart(objworksheet);
WorksheetPart objreplacementPart = objworkbook.AddNewPart<WorksheetPart>();
string objreplacementPartId = objworkbook.GetIdOfPart(objreplacementPart);
Sheets sheets = objworkbook.Workbook.Sheets;
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(objreplacementPart), SheetId = 2, Name = "Sheet" };
sheets.Append(sheet);
// Create object reader to read from excel file.
OpenXmlReader objreader = OpenXmlReader.Create(objworksheet);
// create writer object to write in excel sheet.
OpenXmlWriter objOpenXmwriter = OpenXmlWriter.Create(objreplacementPart);
objOpenXmwriter.WriteStartElement(new Worksheet());
objOpenXmwriter.WriteStartElement(new SheetData());
while (objreader.Read())
{
//read the context of original sheetdata.
//then put all data to new sheetdata by openxmlwriter
}
// this is for Sheetdata
objOpenXmwriter.WriteEndElement();
//* after Sheetdata you can merge cells by openxmlwriter like that:
objOpenXmwriter.WriteStartElement(new MergeCells());
objOpenXmwriter.WriteElement(new MergeCell() { Reference = "P1:Q1" });
objOpenXmwriter.WriteElement(new MergeCell() { Reference = "R1:S1" });
objOpenXmwriter.WriteEndElement();
// this is for Worksheet
objOpenXmwriter.WriteEndElement();
//close all objects
objreader.Close();
objOpenXmwriter.Close();
Sheet sheetreplace = objworkbook.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(objorigninalSheetId)).First();
sheetreplace.Id.Value = objreplacementPartId;
objworkbook.DeletePart(objworksheet);
}
使用Openxml writer在Excel中合并单元格的方式如下:
objOpenXmwriter.WriteStartElement(new MergeCells());
objOpenXmwriter.WriteElement(new MergeCell() { Reference = "P1:Q1" });
objOpenXmwriter.WriteElement(new MergeCell() { Reference = "R1:S1" });
objOpenXmwriter.WriteEndElement();
参考文献: