2016-10-04 75 views
4

我已經嘗試使用如何使用的OpenXML

Bold fbld = new Bold(); 

,大膽的具體文本,但它會大膽大廳細胞使細胞的一些文字加粗。

enter image description here

在這裏,在上述的圖像有一些粗體文本到細胞中。

那麼,它是如何可能在使用C#

回答

5

的OpenXML您需要使用的不同樣式的文本塊獨立Run元素。您可以通過創建一個RunProperties元素並添加一個Bold元素來添加粗體。

下面的代碼將在一個沒有行現有的電子表格的工作(注意,我還沒有添加的代碼合併爲只是增加了複雜性 - 如果你需要提供幫助的話,請參閱my answer here

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true)) 
{ 
    WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart; 

    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; 
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); 
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); 

    //create a row 
    Row row1 = new Row() { RowIndex = 1U }; 

    //create a new inline string cell 
    Cell cell = new Cell() { CellReference = "A1" }; 
    cell.DataType = CellValues.InlineString; 

    //create a run for the bold text 
    Run run1 = new Run(); 
    run1.Append(new Text("ABC")); 
    //create runproperties and append a "Bold" to them 
    RunProperties run1Properties = new RunProperties(); 
    run1Properties.Append(new Bold()); 
    //set the first runs RunProperties to the RunProperties containing the bold 
    run1.RunProperties = run1Properties; 

    //create a second run for the non-bod text 
    Run run2 = new Run(); 
    run2.Append(new Text(Environment.NewLine + "XYZ") { Space = SpaceProcessingModeValues.Preserve }); 

    //create a new inline string and append both runs 
    InlineString inlineString = new InlineString(); 
    inlineString.Append(run1); 
    inlineString.Append(run2); 

    //append the inlineString to the cell. 
    cell.Append(inlineString); 

    //append the cell to the row 
    row1.Append(cell); 

    sheetData.Append(row1); 
} 
+0

謝謝你的回答。 – Divyesh