设置OPEN XML中单元格的粗体和列宽
本文关键字:OPEN XML 单元格 设置 | 更新日期: 2023-09-27 18:28:09
我一直在使用OPEN XML创建一个可以下载的电子表格。我想设置列宽,并将标题更改为粗体。我已经使用Office.Interop.Excel完成了这项工作,但我对这种格式感到很吃力。我的代码在下面,你可以看到我已经设置了一个字体,但无法将其分配给我的电子表格,我收到消息说无法分配给树。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook); //Open(fileName, true);
try
{
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Models" };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Font boldFont = new DocumentFormat.OpenXml.Spreadsheet.Font();
Bold bFontBold = new Bold();
boldFont.Append(bFontBold);
DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
SheetData sheetData = new SheetData();
........
Row row = new Row();
Cell cell = new Cell()
{
CellReference = "A" + (intI + 1),
DataType = CellValues.String,
CellValue = new CellValue(ModelBookrowDetail[0])
};
row.Append(cell);
Cell cell2 = new Cell()
{
CellReference = "B" + (intI + 1),
DataType = CellValues.String,
CellValue = new CellValue(ModelBookrowDetail[1])
};
row.Append(cell2);
.........
sheetData.Append(row);
}
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
spreadsheetDocument.Close();
}
catch
{
spreadsheetDocument.Close();
}
我不知道你对使用OpenXml有多了解。我可能建议查看ClosedXml。到目前为止,它为我节省了很多工时。它只有一个缺点,那就是它不像OpenXml那样管理Word文档。
ClosedXml是一个更面向对象的开源库,与我使用OpenXml的经历相比,它的文档记录得更好。
您可以在此处找到ClosedXml:https://github.com/ClosedXML/ClosedXML
祝好运
嗅觉