Skip to main content
 首页 » 编程设计

c#之如何解决 Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable' ERROR

2024年02月23日20exmyth

我在窗体上有 Devxpress GridControl,
我想将此网格上的数据发送到 excel。
我不想用 ExportToExcel 方法来做到这一点
我用谷歌搜索并找到了这段代码
但此代码用于 .Net 的 DataGrid 控件 并在尝试转换时出错 DevExpress.XtraGrid.Views.Grid.GridView 到 System.Data.DataView
这是代码

public string LastCoulmLetter(int coulmnCount) 
{ 
        string finalColLetter = string.Empty; 
        string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
        int colCharsetLen = colCharset.Length; 
 
        if (coulmnCount > colCharsetLen) 
        { 
            finalColLetter = colCharset.Substring( 
                (coulmnCount - 1) / colCharsetLen - 1, 1); 
        } 
 
        finalColLetter += colCharset.Substring( 
                (coulmnCount - 1) % colCharsetLen, 1); 
 
        return finalColLetter; 
} 
 
 
public void FromGridToExcel() 
{ 
        if (gridView1.RowCount <= 0) 
            return; 
        Excel.Application xls = new Excel.Application(); 
        Excel.Workbook wb; 
        Excel.Worksheet sheet; 
 
        object SalakObje = System.Reflection.Missing.Value; 
        wb = xls.Workbooks.Add(SalakObje); 
        sheet = (Excel.Worksheet)wb.ActiveSheet; 
        sheet.Name = "Result"; 
        xls.Visible = true; 
 
        DataTable dt = (DataTable)gridView1.DataSource; // Error comes in here 
 
        // Copy the DataTable to an object array 
        object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count]; 
 
        // Copy the column names to the first row of the object array 
        for (int col = 0; col < dt.Columns.Count; col++) 
        { 
            rawData[0, col] = dt.Columns[col].ColumnName; 
        } 
 
        // Copy the values to the object array 
        for (int col = 0; col < dt.Columns.Count; col++) 
        { 
            for (int row = 0; row < dt.Rows.Count; row++) 
            { 
                rawData[row + 1, col] = dt.Rows[row].ItemArray[col]; 
            } 
        } 
 
        // Fast data export to Excel 
        string excelRange = string.Format("A1:{0}{1}",LastCoulmLetter(dt.Columns.Count), dt.Rows.Count + 1); 
 
        sheet.get_Range(excelRange, Type.Missing).Value2 = rawData; 
 
        sheet.get_Range(excelRange).Columns.AutoFit(); 
} 

问题是什么以及如何解决

请您参考如下方法:

问题似乎是您的 DataSource 是 DataView,而不是 DataTable。

一些选项:

如果您想使用相同的过滤器,请将其转换为 DataView:

DataView dv = (DataView)gridView1.DataSource; 

如果需要原始数据,请使用 .Table 属性获取源表:

DataTable dt = ((DataView)gridView1.DataSource).Table;