2015-07-21 85 views
1

我使用Office OpenXML来使用Windows服务生成XML文件。代码工作正常,并生成excel文件。但是现在我想为行和单元添加一些样式。我怎样才能做到这一点? 我使用的代码是:将样式应用于使用office open xml生成的excel文件C#

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的实现造型?

回答

0

你应该添加样式到您的工作表
喜欢这个

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 
+0

在哪里定义此AddStyles函数?然后在哪里使用它? – Priya

+0

你可以在你想要的地方做到这一点。例如,我打开文档进行修改时调用此函数。在此之后'使用(SpreadsheetDocument文档= SpreadsheetDocument.Open(FilePath,true)) var styleSheet = document.WorkbookPart.WorkbookStylesPart.Stylesheet;'您应该在类中修改excel文档 – Disappointed

+0

Spreadsheet包含哪些名称空间? – Priya