2012-12-27 106 views
6

如何在OpenXml中設置一行(或整行)內的幾個單元格的背景?如何設置單元格的背景?

看了幾篇文章:

  1. Coloring cells in excel sheet using openXML in C#
  2. Advanced styling in Excel Open XML

我仍然不能使它發揮作用。

我的任務實際上乍看起來似乎比這些文章中寫的更容易一些,有點不同。上述教程主要展示如何創建一個新文檔並對其進行設計。雖然我需要改變現有的造型。

也就是說,我有一個現有的xlsx文檔(報告模板)。我用必要的值填充報告(設法通過SO open xml excel read cell valueMSDN Working with sheets (Open XML SDK)來完成)。但接下來我需要用紅色背景標記幾行。

我既不知道是否使用CellStyle也不如果我要使用CellFormat還是其他什麼東西......這就是我起身到現在:

SpreadsheetDocument doc = SpreadsheetDocument.Open("ole.xlsx", true); 

Sheet sheet = (Sheet)doc.WorkbookPart 
         .Workbook 
         .Sheets 
         .FirstOrDefault(); 

WorksheetPart worksheetPart = (WorksheetPart)doc.WorkbookPart 
               .GetPartById(sheet.Id); 
Worksheet worksheet = worksheetPart.Worksheet; 


CellStyle cs = new CellStyle(); 
cs.Name = StringValue.FromString("Normal"); 
cs.FormatId = 0; 
cs.BuiltinId = 0; 
//where are the style values? 

WorkbookStylesPart wbsp = doc.WorkbookPart 
           .GetPartsOfType<WorkbookStylesPart>() 
           .FirstOrDefault(); 
wbsp.Stylesheet.CellStyles.Append(cs); 
wbsp.Stylesheet.Save(); 



Cell cell = GetCell(worksheet, "A", 20); 
cell.StyleIndex = 1U;//get the new cellstyle index somehow 

doc.Close(); 

其實,我將不勝感激,更光重量和簡單的例子如何風格,說,單元格A20或範圍從A20J20。或者可能是一些更連續教程的鏈接。

回答

5

最後,我改變了主意,使用單元格背景和使用字體。由於通過回答foson在SO Creating Excel document with OpenXml sdk 2.0我設法添加新Font和新CellFormat,已經保留了原來的單元格的格式(即具有唯一改變字體顏色):

SpreadsheetDocument doc = SpreadsheetDocument.Open("1.xlsx", true); 
Sheet sheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.FirstOrDefault(); 
WorksheetPart worksheetPart = (WorksheetPart)doc.WorkbookPart 
               .GetPartById(sheet.Id); 
Worksheet worksheet = worksheetPart.Worksheet; 

WorkbookStylesPart styles = doc.WorkbookPart.WorkbookStylesPart; 
Stylesheet stylesheet = styles.Stylesheet; 
CellFormats cellformats = stylesheet.CellFormats; 
Fonts fonts = stylesheet.Fonts; 

UInt32 fontIndex = fonts.Count; 
UInt32 formatIndex = cellformats.Count; 

Cell cell = GetCell(worksheet, "A", 19); 
cell.CellValue = new CellValue(DateTime.Now.ToLongTimeString()); 
cell.DataType = new EnumValue<CellValues>(CellValues.String); 

CellFormat f = (CellFormat)cellformats.ElementAt((int)cell.StyleIndex.Value); 

var font = (Font)fonts.ElementAt((int)f.FontId.Value); 
var newfont = (Font)font.Clone(); 
newfont.Color = new Color() { Rgb = new HexBinaryValue("ff0000") }; 
fonts.Append(newfont); 

CellFormat newformat = (CellFormat)f.Clone(); 
newformat.FontId = fontIndex; 
cellformats.Append(newformat); 

stylesheet.Save(); 

cell.StyleIndex = formatIndex; 
doc.Close(); 
相關問題