Domanda

Ho creato un documento Excel usando OpenXml SDK 2.0, ora devo modificarlo, ma non posso.

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

Il mio codice per creare una cella è:

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;
} 
È stato utile?

Soluzione

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

Il mio metodo generale per gestire l'SDK OpenXML è quello di 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 cambiamenti devono essere fatto per implementare la funzione.

Se stai creando un documento da zero, puoi utilizzare DocumentReflector per generare il codice per l'oggetto Stylesheet predefinito e quindi aggiungere gli stili che ti servono.

A partire dall'impostazione predefinita:

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 carattere di dimensione 12 e un nuovo riempimento con sfondo rosso (valore indicizzato 64) e ho aggiunto nuovi CellFormat che fanno riferimento all'indice del nuovo carattere e riempimento. (Assicurati di aggiornare anche i conteggi)

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" });

Quindi, nel codice, applico l'indice CellStyle alle celle che voglio formattare: (Esistevano già dati nelle celle A2 e A3. La cella A2 ha dimensioni maggiori, 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;

Altri suggerimenti

Mille grazie per questo articolo.

Dopo molte lotte (e googling), sono finalmente riuscito a creare una classe C # molto facile da usare, che prende un DataSet e un Nome file e crea un Office 2007 .xlsx contenente i dati del DataSet.

All'improvviso, il processo di aggiunta di una funzione alla tua applicazione per " Esporta in Excel " diventa facile come ...

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

CreateExcelFile.CreateExcelDocument(ds, excelFilename);

Ho pubblicato il codice sorgente completo, oltre a un esempio di utilizzo, sul seguente sito Web.

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

Enjoy.

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

Come specificare uno stile di cella?

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

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top