使用Open Xml将数据从gridview导出到Excel

时间:2013-02-11 22:48:39

标签: c# asp.net openxml

所以我认为我已经掌握了基本的机制,但我的数据没有被导出。我跟着这个Blog,我的情况有所不同,因为我正在创建一个有两张纸但没有达到这一点的工作簿,因为我不能得到第一张纸来填充。

基本上,我正在获取一些填充两个网格视图的数据,在按钮事件中我做了所有这些工作。文件名是根据用户选择生成的,但是agian是非问题,实例化电子表格对象,添加工作簿电子表格等等。

到目前为止,我只编写了第一个电子表格的部分,这是我的代码的样子。提前谢谢 - 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();

    // Create sheet object
    SheetData _sheetData = new SheetData();

    // Initialize row index
    UInt32Value _currRowIndex = 1U;
    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;

            // Add teh value to the cell
            _cell.Append(_cellVallue);

            // Add the cell to the row
            _excelRow.Append(_cell);
        }

        // Add the row to the sheet
        _sheetData.Append(_excelRow);
    }

    _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();
} 

2 个答案:

答案 0 :(得分:0)

如果您正在使用SQL Server并且它适用于您的情况,那么最好使用SSRS为您生成excel文件。我研究了使用直接Open XML方法,但发现SSRS更适合我的需求。完全取决于您的要求。

答案 1 :(得分:0)

尝试使用此博客中的代码

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