开发者

Open XML Excel Cell Formatting

开发者 https://www.devze.com 2023-02-15 00:39 出处:网络
I am trying to export to excel using Open XML with simple formatting. Export to Excel is working. The problem is with formatting the data. I am trying to have very basic formatting. i.e. the Column na

I am trying to export to excel using Open XML with simple formatting. Export to Excel is working. The problem is with formatting the data. I am trying to have very basic formatting. i.e. the Column names should be in bold and rest of the content in normal font. This is what I did. Please let me know where am I going wrong.

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(Resp开发者_如何学运维onse.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;
        }

    }


It seems like you are missing a ")" after your first font creation. So then you end opp with only one font index (the default one) Below is the code I use for exactly what you are asking for. You might remove fills and borders and remove them from cellformat, but I had some syntax problems while writing this so I just left it when it all worked :-)

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

精彩评论

暂无评论...
验证码 换一张
取 消