gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:17 27 4
gpt4 key购买 nike

我在窗体上有 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();
}

问题是什么以及如何解决

最佳答案

问题似乎是您的 DataSourceDataView,而不是 DataTable

一些选项:

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

DataView dv = (DataView)gridView1.DataSource;

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

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

关于c# - 如何解决 Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable' ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com