2015-07-21 91 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