应用样式的excel文件生成使用office打开xml c#
本文关键字:office 打开 xml 样式 excel 文件 应用 | 更新日期: 2023-09-27 18:03:58
我使用Office OpenXML使用windows服务生成XML文件。代码工作良好,并生成excel文件。现在我想给行和单元格添加一些样式。我怎样才能做到呢?我使用的代码是:
if (thermoCoupleList.Count > 0)
{
FileInfo newFile = new FileInfo(filePath);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("ThermoCouples");
// write some titles into row 1
worksheet.Cell(1, 1).Value = "Thermocouple ID";
worksheet.Cell(1, 2).Value = "Calibration Done Date";
worksheet.Cell(1, 3).Value = "Calibration Due Date";
worksheet.Cell(1, 4).Value = "Company";
int col, row = 1;
foreach (Thermocouples tc1 in thermoCoupleList)
{
col = 1;
row = row + 1;
worksheet.Cell(row, col++).Value = Convert.ToString(tc1.ThermocoupleIdentification);
worksheet.Cell(row, col++).Value = tc1.CalibrationDoneDate;
worksheet.Cell(row, col++).Value = tc1.CalibrationDueDate;
worksheet.Cell(row, col++).Value = tc1.Company;
}
xlPackage.Save();
}
}
如何在Office OpenXML中实现样式?
首先你应该给你的表单添加样式
这样的
private void AddStyles(Stylesheet styleSheet)
{
var patternFill = new PatternFill
{
PatternType = PatternValues.Solid,
ForegroundColor = new ForegroundColor { Rgb = "FFFF0000" },
BackgroundColor = new BackgroundColor { Indexed = 64U }
};
var fill = new Fill { PatternFill = patternFill };
styleSheet.Fills.AppendChild(fill);
}
样式表对象,例如可以通过以下方式获得
using (SpreadsheetDocument document = SpreadsheetDocument.Open(FilePath, true))
{
var styleSheet= document.WorkbookPart.WorkbookStylesPart.Stylesheet;
}
你的每个样式都有一些索引。您可以将此样式索引分配给单元格。使用这个属性
DocumentFormat.OpenXml.Spreadsheet.Cell.StyleIndex