将网格视图导出到excel窗体C# [英] Export grid view to excel windows form C#

查看:65
本文介绍了将网格视图导出到excel窗体C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好吧

i有agridview的devexpress我需要将网格内容导出到excel表我已经使用了以下代码我只有一行错误

Hi everybody
i have devexpress with agridview i need to export grid content to excel sheet i have used the following code i only have one error in the line

gridView1.GetDataRow(I).Cells[j].Value;



我该如何解决它



我尝试过:




how can i solve it

What I have tried:

int rowsTotal = 0;
int colsTotal = 0;
int I = 0;
int j = 0;
int iC = 0;
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
Excel.Application xlApp = new Excel.Application();

try
{
    Excel.Workbook excelBook = xlApp.Workbooks.Add();
    Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelBook.Worksheets[1];
    xlApp.Visible = true;

    rowsTotal = gridView1.RowCount - 1;
    colsTotal = gridView1.Columns.Count - 1;
    var _with1 = excelWorksheet;
    _with1.Cells.Select();
    _with1.Cells.Delete();
    for (iC = 0; iC <= colsTotal; iC++)
    {
        _with1.Cells[1, iC + 1].Value = gridView1.Columns[iC].Caption;
    }
    for (I = 0; I <= rowsTotal - 1; I++)
    {
        for (j = 0; j <= colsTotal; j++)
        {
            _with1.Cells[I + 2, j + 1].value = gridView1.GetDataRow(I).Cells[j].Value;
            //  _with1.Cells[I + 2, j + 1].value = gridView1.GetRowCellValue(I).ToString();
        }
    }
    _with1.Rows["1:1"].Font.FontStyle = "Bold";
    _with1.Rows["1:1"].Font.Size = 12;

    _with1.Cells.Columns.AutoFit();
    _with1.Cells.Select();
    _with1.Cells.EntireColumn.AutoFit();
    _with1.Cells[1, 1].Select();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    //RELEASE ALLOACTED RESOURCES
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
    xlApp = null;
}

推荐答案

您遇到的问题是什么?在凝视着我的水晶球后,我打赌你得到的索引超出范围异常。



根据我的经验,Excel的行和列是1索引的而不是0索引。
WHAT PROBLEM ARE YOU SEEING? After gazing into my crystal ball, I bet you're getting an "index out of range exception".

In my experience, Excel's rows and columns are 1-indexed instead of 0-indexed.


这篇关于将网格视图导出到excel窗体C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆