简体   繁体   中英

Export data from gridview to Excel with Open Xml

So I think I've got the basic mechanics down, yet my data is not being exported. I've followed this Blog and my situation is somewhat different in that I'm creating a workbook with two sheets but haven't gotten to that point because I can't eve get the first sheet to populate.

Basically, I'm fetching some data populating two gridviews, the on a button event I do all this work. File names are being generated based on user selection but again that is a non-issue, the instnantiating a spreadsheet object, adding a workbook the spreadsheet, and so on.

So far I've coded only the part for the first spreadsheet and here is what my code looks like. Thanks in advance - Risho.

public void btnExport_Click(object sender, System.EventArgs e)
{
    string fileName1 = string.Empty;
    string sheetName1 = "XXXXX Output";
    string sheetName2 = "YYYYY Output";
    if (ddlIntervals.SelectedValue.ToString() == "3")
    {
        fileName1 = @"C:\Temp\XY_Totals_" + ddlSites.SelectedItem.ToString() + ".xlsx";
    }
    else if (ddlIntervals.SelectedValue.ToString() == "2")
    {
        fileName1 = @"C:\Temp\XYbyYear_" + ddlSites.SelectedItem.ToString() + ".xlsx";
    }
    else
    {
        fileName1 = @"C:\Temp\XYByMonth_" + ddlSites.SelectedItem.ToString() + ".xlsx";
    }
    // Create a spreadsheet document by supplying the file name.
    SpreadsheetDocument _spreadsheetDocument = SpreadsheetDocument.Create(fileName1, SpreadsheetDocumentType.Workbook);
    // Add a WorkbookPart to the document.
    WorkbookPart _workbookPart = _spreadsheetDocument.AddWorkbookPart();
    _workbookPart.Workbook = new Workbook();
    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart _worksheetPart = _workbookPart.AddNewPart<WorksheetPart>();
    // Add Sheets to the Workbook
    Sheets _sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
    // Append a new worksheet and associate it with the workbook.
    Sheet _sheet = new Sheet() { Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(_worksheetPart), SheetId = 1, Name = sheetName1 };
    _sheets.Append(_sheet);
    //_worksheetPart.Worksheet = new Worksheet(new SheetData());
    Worksheet _worksheet = new Worksheet();
    SheetData _sheetData = new SheetData();    // Create sheet object
    UInt32Value _currRowIndex = 1U;   // Initialize row index
    int _colIndex = 0;
    Row _excelRow;
    // Iterate through table rows and add them to the worksheet
    // we're starting with roindex -1 instesd of zero, as we create a header row first
    for (int rowindex = -1; rowindex < GridView1.Rows.Count; rowindex++)
    {
        _excelRow = new Row();
        _excelRow.RowIndex = _currRowIndex++;
        for (_colIndex = 0; _colIndex < GridView1.Columns.Count; _colIndex++)
        {
            Cell _cell = new Cell()
            {
                // Create the cell reference of format A1, B2, etc.
                CellReference = Convert.ToString(Convert.ToChar(65 + _colIndex)),
                DataType = CellValues.String
            };
            CellValue _cellVallue = new CellValue();
            // If it's a header row, cell value will be nothing but column name
            // It if a not header row, set the column value to the cell
            if (rowindex == -1)
                _cellVallue.Text = GridView1.Columns[_colIndex].HeaderText.ToString();
            else
                _cellVallue.Text = GridView1.Rows[rowindex].Cells[_colIndex].Text;
            _cell.Append(_cellVallue); // Add the value to the cell
            _excelRow.Append(_cell);   // Add the cell to the row
        }
        _sheetData.Append(_excelRow);  // Add the row to the sheet
    }
    _worksheet.Append(_sheetData);
    _worksheetPart.Worksheet =_worksheet;
    Sheet _sheet2 = new Sheet() { Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(_worksheetPart), SheetId = 2, Name = sheetName2 };
    _sheets.Append(_sheet2);
    _workbookPart.Workbook.Save();
    //Close the document.
    //_spreadsheetDocument.Close();
} 

If you're using SQL Server and it works with your situation you might be better off using SSRS to generate the excel file for you. I looked into using the direct Open XML method, but found that SSRS would be better suited to my needs. Totally depends on your requirements.

Try the code from this blog it is working

"codeproject.com/Tips/366446/Export-GridView-Data-to-Excel-using-OpenXml"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM