打开XML Excel单元格格式

时间:2011-03-04 15:14:20

标签: cell spreadsheet openxml export-to-excel

我正在尝试使用简单格式的Open XML导出到Excel。导出到Excel正在运行。问题在于格式化数据。我想要有非常基本的格式。即列名称应为粗体,其余内容为普通字体。这就是我做的。请告诉我哪里出错了。

private Stylesheet GenerateStyleSheet()
{
    return new Stylesheet(
        new Fonts(
            new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12},
                new Bold(),
            new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12}))
        )
    );
}
 protected void ExportExcel(DataTable dtExport)
    {
        Response.ClearHeaders();
        Response.ClearContent();
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
        //"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" '"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" '"application/vnd.ms-excel"
        Response.AddHeader("content-disposition", "attachment; filename=Test.xlsx");
        Response.Charset = "";
        this.EnableViewState = false;
        MemoryStream ms = new MemoryStream();
        SpreadsheetDocument objSpreadsheet = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
        WorkbookPart objWorkbookPart = objSpreadsheet.AddWorkbookPart();
        objWorkbookPart.Workbook = new Workbook();
        WorksheetPart objSheetPart = objWorkbookPart.AddNewPart<WorksheetPart>();
        objSheetPart.Worksheet = new Worksheet(new SheetData());
        Sheets objSheets = objSpreadsheet.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
        Sheet objSheet = new Sheet();
        objSheet.Id = objSpreadsheet.WorkbookPart.GetIdOfPart(objSheetPart);
        objSheet.SheetId = 1;
        objSheet.Name = "mySheet";
        objSheets.Append(objSheet);

        WorkbookStylesPart stylesPart = objSpreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
        stylesPart.Stylesheet = GenerateStyleSheet();
        stylesPart.Stylesheet.Save();
        objSheetPart.Worksheet.Save();

        objSpreadsheet.WorkbookPart.Workbook.Save();
        for (int cols = 0; cols < dtExport.Columns.Count; cols++)
        {
            Cell objCell = InsertCellInWorksheet(GetColumnName(cols), 1, objSheetPart);
            objCell.CellValue = new CellValue(dtExport.Columns[cols].ColumnName);
            objCell.DataType = new EnumValue<CellValues>(CellValues.String);
            objCell.StyleIndex = 0;
        }
        objSheetPart.Worksheet.Save();
        objSpreadsheet.WorkbookPart.Workbook.Save();
        for (uint row = 0; row < dtExport.Rows.Count; row++)
        {
            for (int cols = 0; cols < dtExport.Columns.Count; cols++)
            {
                //row + 2 as we need to start adding data from second row. First row is left for header
                Cell objCell = InsertCellInWorksheet(GetColumnName(cols), row + 2, objSheetPart);
                objCell.CellValue = new CellValue(Convert.ToString(dtExport.Rows[Convert.ToInt32(row)][cols]));
                objCell.DataType = new EnumValue<CellValues>(CellValues.String);
                objCell.StyleIndex = 1;
            }
        }
        objSheetPart.Worksheet.Save();
        objSpreadsheet.WorkbookPart.Workbook.Save();
        objSpreadsheet.Close();
        ms.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();

    }
 // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. 
    // If the cell already exists, return it. 
    private Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
    {
        Worksheet worksheet = worksheetPart.Worksheet;
        SheetData sheetData = worksheet.GetFirstChild<SheetData>();
        string cellReference = (columnName + rowIndex.ToString());

        // If the worksheet does not contain a row with the specified row index, insert one. 
        Row row = default(Row);

        if ((sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).Count() != 0))
        {
            row = sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).First();
        }
        else
        {
            row = new Row();
            row.RowIndex = rowIndex;
            sheetData.Append(row);
        }

        // If there is not a cell with the specified column name, insert one. 
        if ((row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex.ToString()).Count() > 0))
        {
            return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
        }
        else
        {
            // Cells must be in sequential order according to CellReference. Determine where to insert the new cell. 
            Cell refCell = null;
            foreach (Cell cell in row.Elements<Cell>())
            {
                if ((string.Compare(cell.CellReference.Value, cellReference, true) > 0))
                {
                    refCell = cell;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
            Cell newCell = new Cell();
            newCell.CellReference = cellReference;

            row.InsertBefore(newCell, refCell);
            return newCell;
        }

    }

1 个答案:

答案 0 :(得分:1)

在第一次创建字体后,您似乎错过了“)”。那么你只用一个字体索引(默认的一个)结束对手 下面是我正在使用的代码。 你可能会删除填充和边框并从cellformat中删除它们,但是在写这个时我遇到了一些语法问题,所以当它全部工作时我就离开了它: - )

 private Stylesheet GenerateStyleSheet()
    {
        return new Stylesheet(
            new Fonts(
                // Index 0 - Default font.
                new Font(                                                               
                    new FontSize() { Val = 11 },
                    new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
                    ),
                new Font(                                                               
                    new Bold(),
                    new FontSize() { Val = 11 },
                    new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
                    )
            ),
            new Fills(
                // Index 0 - Default fill.
                new Fill(                                                           
                    new PatternFill() { PatternType = PatternValues.None })
            ),
            new Borders(
                // Index 0 - Default border.
                new Border(                                                         
                    new LeftBorder(),
                    new RightBorder(),
                    new TopBorder(),
                    new BottomBorder(),
                    new DiagonalBorder())
            ),
            new CellFormats(
                // Index 0 - Default cell style
                new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },                            
                new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }         
            )
        );
    }