2009-06-18 20 views
15

Ho creato un documento Excel utilizzando OpenXml SDK 2.0, ora devo definirlo, ma non posso.Creazione di un documento Excel con OpenXml sdk 2.0

Non so come dipingere il colore di sfondo o modificare la dimensione del carattere in celle diverse.

Il mio codice per creare una cellula è:

private static Cell CreateTextCell(string header, string text, UInt32Value index) 
{ 
    Cell c = new Cell(); 
    c.DataType = CellValues.InlineString; 
    c.CellReference = header + index; 
    InlineString inlineString = new InlineString(); 
    DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); 
    t.Text = text; 
    inlineString.AppendChild(t); 
    c.AppendChild(inlineString); 
    return c; 
} 

risposta

18

Nota: OpenXML 2.0 SDK è attualmente in CTP e non è autorizzato per l'uso in produzione fino Office2010.

Il mio metodo generale per trattare con OpenXML SDK è creare un documento vuoto e un documento con solo le funzionalità che desideri imparare come implementare (come il colore di sfondo) e utilizzare OpenXmlDiff dell'SDK per vedere quali modifiche devono essere fatto per implementare la funzione.

Se si sta creando un documento da zero, è possibile utilizzare DocumentReflector per generare il codice per l'oggetto Stylesheet predefinito e quindi aggiungere gli stili necessari.

A partire con il default:

new Stylesheet(
new Fonts(
    new Font(
     new FontSize() { Val = 10D }, 
     new Color() { Theme = (UInt32Value)1U }, 
     new FontName() { Val = "Arial" }, 
     new FontFamilyNumbering() { Val = 2 }) 
) { Count = (UInt32Value)1U }, 
new Fills(
    new Fill(
     new PatternFill() { PatternType = PatternValues.None }), 
    new Fill(
     new PatternFill() { PatternType = PatternValues.Gray125 }) 
) { Count = (UInt32Value)2U }, 
new Borders(... 
... 
... 
new CellFormats(
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }) { Count = (UInt32Value)1U }, ... 

Ho aggiunto un nuovo font di dimensione 12 e un nuovo riempimento con lo sfondo rosso (valore indicizzato 64), e aggiunto nuove CellFormats che fanno riferimento l'indice della nuova Carattere e riempimento. (Assicurati di aggiornare i conti troppo)

new Stylesheet(
    new Fonts(
     new Font(
      new FontSize() { Val = 10D }, 
      new Color() { Theme = (UInt32Value)1U }, 
      new FontName() { Val = "Arial" }, 
      new FontFamilyNumbering() { Val = 2 }), 
     new Font(
      new FontSize() { Val = 12D }, 
      new Color() { Theme = (UInt32Value)1U }, 
      new FontName() { Val = "Arial" }, 
      new FontFamilyNumbering() { Val = 2 }) 
      ) { Count = (UInt32Value)2U }, 
    new Fills(
     new Fill(
      new PatternFill() { PatternType = PatternValues.None }), 
     new Fill(
      new PatternFill() { PatternType = PatternValues.Gray125 }), 
     new Fill(
      new PatternFill() { PatternType = PatternValues.Solid, ForegroundColor = new ForegroundColor() { Rgb = "FFFF0000" }, BackgroundColor = new BackgroundColor() { Indexed = 64 } }) 
      ) { Count = (UInt32Value)3U }, 
    new Borders(
     new Border(
      new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder()) 
    ) { Count = (UInt32Value)1U }, 
    new CellStyleFormats(
     new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U } 
    ) { Count = (UInt32Value)1U }, 
    new CellFormats(
     new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, 
     new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, 
     new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U } 
    ) { Count = (UInt32Value)3U }, 
    new CellStyles(
     new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U } 
    ) { Count = (UInt32Value)1U }, 
    new DifferentialFormats() { Count = (UInt32Value)0U }, 
    new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" }); 

Poi, nel codice, applico l'indice CellStyle alle cellule voglio formattare:. (C'era già dati nelle celle A2 e A3 cellulare A2 ottiene il più grande, A3 diventa sfondo rosso)

SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); 
sheetData.Descendants<Row>().Where(r => r.RowIndex == 2U).First().Descendants<Cell>().First().StyleIndex = 1U; 
sheetData.Descendants<Row>().Where(r => r.RowIndex == 3U).First().Descendants<Cell>().First().StyleIndex = 2U; 
+0

+1 Grazie mille. Il tuo post mi ha dato una buona partenza in effetti. – horgh

2

Come specificare uno stile di cella?

new Cell() { CellReference = "B6", StyleIndex = 11U } 

Qui "11U" è un indice a base zero StylesPart.Stylesheet.CellFormats, in cui ogni CellFormat definisce una combinazione di NumberFormat, font, riempimento e stili di bordo.

Non è necessario aggiungere tutti gli stili per programma, è possibile invece creare un file xlsx modello con tutti i formati necessari al suo interno e quindi specificare l'indice di stile nel programma.

+0

Ciao Hailaing Wang. Non sono sicuro di ciò che hai menzionato su come modificare uno stile di una cella. Come si ottiene StyleIndex = 11U. Ciò di cui ho bisogno nel mio caso è di avere i confini della cella. Ho anche bisogno di avere uno sfondo blu. Puoi rispondere a http://stackoverflow.com/questions/15791732/openxml-sdk-having-borders-for-cell. Grazie in anticipo –

9

Mille grazie per questo articolo.

Dopo un sacco di lottare (e usare Google), sono finalmente riuscito a creare un facile da usare C# classe molto, che prende un DataSet e un nome di file e crea un Office 2007 xlsx contenente i dati del DataSet .

Improvvisamente, il processo di aggiunta di una funzione per l'applicazione per "Esporta in Excel" diventa facile come ...

DataSet ds = CreateSampleData();     // Your code here ! 
string excelFilename = "C:\\Sample.xlsx"; 

CreateExcelFile.CreateExcelDocument(ds, excelFilename); 

ho postato il codice sorgente completo, più un esempio di utilizzo di esso , sul seguente sito Web.

È un'applicazione di Visual Studio 2008 C# WinForms, ma è possibile consentire a Visual Studio di aggiornare questo progetto, se si esegue VS2010.

Divertiti.

http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

+0

Dal tuo blog: * Non ho aggiunto una licenza, poiché si tratta di codice libero, da utilizzare come desideri. * Realtà giuridica: * l'assenza di una licenza implica l'applicazione delle leggi sul copyright di default * (disclaimer - IANAL - Non sono un avvocato) –

Problemi correlati