2011-08-30 81 views
6

使用Open XML for Excel和DocumentFormat.OpenXml.Spreadsheet,如何只將部分文本設置爲粗體?Open XML SDK:格式化Excel單元格的一部分

var cell = new Cell { 
    //DataType = CellValues.InlineString, 
    CellReference = "A" + 1 
}; 

// TODO: Set "bold text" to bold style 
//var inlineString = new InlineString(); 
//inlineString.AppendChild(new Text { Text = "Normal text... bold text..." }); 
//cell.AppendChild(inlineString); 

註釋掉現在使用的代碼,但應該或應該更改。

回答

6

要僅將部分文本設置爲粗體,您需要將文本插入到SharedStringTable中,並將單元格的數據類型設置爲SharedString而不是InlineString來控制該文本。這將使CellValue成爲此表中的引用,如0,1,2等,並允許更多控制,然後執行內聯字符串。

這裏是如何使pharse的第二部分,一些示例代碼「普通文本......大膽的文字......」大膽:

 // Creates an SharedStringItem instance and adds its children. 
     public SharedStringItem GenerateSharedStringItem() 
     { 
      SharedStringItem sharedStringItem1 = new SharedStringItem(); 

      Run run1 = new Run(); 
      Text text1 = new Text(){ Space = SpaceProcessingModeValues.Preserve }; 
      text1.Text = "Normal text… "; 

      run1.Append(text1); 

      Run run2 = new Run(); 

      RunProperties runProperties1 = new RunProperties(); 
      Bold bold1 = new Bold(); 
      FontSize fontSize1 = new FontSize(){ Val = 11D }; 
      Color color1 = new Color(){ Theme = (UInt32Value)1U }; 
      RunFont runFont1 = new RunFont(){ Val = "Calibri" }; 
      FontFamily fontFamily1 = new FontFamily(){ Val = 2 }; 
      FontScheme fontScheme1 = new FontScheme(){ Val = FontSchemeValues.Minor }; 

      runProperties1.Append(bold1); 
      runProperties1.Append(fontSize1); 
      runProperties1.Append(color1); 
      runProperties1.Append(runFont1); 
      runProperties1.Append(fontFamily1); 
      runProperties1.Append(fontScheme1); 
      Text text2 = new Text(); 
      text2.Text = "bold text…"; 

      run2.Append(runProperties1); 
      run2.Append(text2); 

      sharedStringItem1.Append(run1); 
      sharedStringItem1.Append(run2); 
      return sharedStringItem1; 
     } 

要使用你想先找到這個方法在SharedStringTable然後實例插入新的ShareStringItem到它:

  using (MemoryStream stream = new MemoryStream()) 
      { 
       // create in-memory copy of the Excel template file 
       byte[] byteArray = File.ReadAllBytes(TEMPLATE_FILE_NAME); 
       stream.Write(byteArray, 0, (int)byteArray.Length); 

       using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, true)) 
       { 
        // Set private variable template component references (for reuse between methods) 
        mExcelWorkbookPart = document.WorkbookPart; 
        mSharedStringTablePart = mExcelWorkbookPart.SharedStringTablePart; 

        mSharedStringTablePart.SharedStringTable.AppendChild(GenerateSharedStringItem()); 
       } 

       return stream.ToArray(); 
      } 
+0

嗨amurra,你能幫助我http://stackoverflow.com/questions/15791732/openxml-sdk-having-borders-for-cell 。不知道如何讓一個單元格有邊界。謝謝 –

相關問題