0

I populate values from my gridview in my table using this Code:

Table table = new Table();

 // get gridlines from gridview
table.GridLines = GridView1.GridLines;

if (GridView1.HeaderRow != null)
{
    table.Rows.Add(GridView1.HeaderRow);
}

foreach (GridViewRow row in GridView1.Rows)
{
    table.Rows.Add(row);
}

if (GridView1.FooterRow != null)
{
    table.Rows.Add(GridView1.FooterRow);
}

What I need is to read every data from the table which contains the values of the gridview into an Excel worksheet cell. How can I achieve this?

PS: This is my worksheet obj in code-behind in C#.

Excel.Workbook xlWorkBook;
     Excel.Worksheet xlWorkSheet;

Or Is there any other way to add the data from GridView to something else than, using table, which can be easily read?

4

1 回答 1

0
    public void ExportToExcel()
    {
        var Excel = new Microsoft.Office.Interop.Excel.Application();
        XlReferenceStyle RefStyle = Excel.ReferenceStyle;
        Excel.Visible = true;
        Workbook wb = null;
        string path = "yourpath";
        try
        {
            wb = Excel.Workbooks.Add(path); 
        }
        catch (System.Exception ex) 
        { 
            throw new Exception(ex.Message); 
        }
        Worksheet ws = wb.Worksheets.get_Item(1) as Worksheet ;
        for (int j = 0; j < GridView1.Columns.Count; ++j)
        {
            (ws.Cells[1, j + 1] as Range).Value2 = GridView1.Columns[j].HeaderText;
            for (int i = 0; i < GridView1.Rows.Count; ++i) 
            {
                object Val = GridView1.Rows[i].Cells[j].Value;
                if (Val != null)
                    (ws.Cells[i + 2, j + 1] as Range).Value2 = Val.ToString();
            }
        }
        Excel.ReferenceStyle = RefStyle;
        Marshal.ReleaseComObject((object)Excel);         
        GC.GetTotalMemory(true); 
    }

是的,有很多方法取决于你要做什么。在您的情况下,最简单的一个是 CSV 文件(可以很好地使用 Excel)。如果您有 DataSource,则无需对 DataGridView 做任何事情

于 2012-12-07T07:47:15.550 回答