2009-06-18 25 views
15

He creado un documento Excel usando OpenXML SDK 2.0, ahora tengo que darle estilo, pero no puedo.Creando documento Excel con OpenXML sdk 2.0

No sé cómo pintar el color de fondo o cambiar el tamaño de la fuente en diferentes celdas.

Mi código para crear una célula es:

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

Respuesta

18

Nota: OpenXML 2.0 SDK está actualmente en CTP y no tiene licencia para su uso en producción hasta Office2010.

Mi método general para tratar con OpenXML SDK es crear un documento en blanco y un documento con solo las características que desea aprender a implementar (como color de fondo) y usar el SDX OpenXmlDiff para ver qué cambios necesitan estar hecho para implementar la característica.

Si está creando un documento desde cero, puede usar DocumentReflector para generar el código para el objeto predeterminado Stylesheet y luego agregar los estilos que necesita.

Comenzando con el valor por defecto:

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 }, ... 

He añadido una nueva fuente de tamaño 12 y un nuevo relleno con el fondo rojo (indexado 64), y añadí nuevas CellFormats que hacen referencia al índice de la nueva Fuente y relleno (Asegúrese de actualizar los Condes demasiado)

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

Luego, en el código, aplico el índice CellStyle a las células Quiero dar formato:. (Ya había datos en las celdas A2 y A3 celda A2 obtiene el tamaño más grande, A3 obtiene fondo rojo)

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 Muchísimas gracias. Tu publicación me dio un buen comienzo de hecho. – horgh

2

¿Cómo especificar un estilo de celda?

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

aquí "11U" es un índice basado en cero de StylesPart.Stylesheet.CellFormats, en el que cada CellFormat define una combinación de NumberFormat, Font, llenado y estilos de borde.

No tiene que agregar todos los estilos por programa, en su lugar puede crear una plantilla de archivo xlsx con todos los formatos que necesita, y luego especificar el índice de estilo en su programa.

+0

Hola Hailaing Wang. No estoy seguro de lo que mencionaste sobre cómo modificar un estilo de una celda. ¿Cómo se obtiene StyleIndex = 11U? Lo que necesito en mi caso es que la celda tenga bordes. También necesito que tenga un fondo azul. ¿Puedes responder a http://stackoverflow.com/questions/15791732/openxml-sdk-having-borders-for-cell. Gracias de antemano –

9

Muchas gracias por este artículo.

Después de mucha lucha (y googlear), que finalmente lograron crear un fácil de usar C# clase muy, que tiene un conjunto de datos y un nombre de archivo y crea una Oficina 2007 .xlsx que contienen los datos del conjunto de datos .

De repente, el proceso de agregar una función a su aplicación a "Exportar a Excel" se vuelve tan fácil como ...

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

CreateExcelFile.CreateExcelDocument(ds, excelFilename); 

He publicado el código fuente completo, además de un ejemplo de su uso , en el siguiente sitio web.

Es una aplicación Visual Studio 2008 C# WinForms, pero puede dejar que Visual Studio actualice este proyecto, si está ejecutando VS2010.

disfrutar.

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

+0

De tu blog: * No he agregado una licencia, ya que es un código gratuito, para usar como desees. * Realidad legal: * la ausencia de una licencia significa que se aplican las leyes de copyright predeterminadas * (descargo de responsabilidad - IANAL - No soy abogado) –

Cuestiones relacionadas