2012-01-24 8 views
1

フォームにDevxpress GridControlがあります。
このグリッドのデータをExcelに送信したい。
と私はGoogleで検索して、このコード
が見つかりましたが、このコードはネット のDataGridコントロールのためであり、それは DevExpress.XtraGrid.Viewsを変換しようとすると、エラーを与えているExportToExcel方法
でこれをやりたいいけませんSystem.Data.DataView
ここに.Grid.GridViewは解決方法 'System.Data.DataView'タイプのオブジェクトをキャストできません 'System.Data.DataTable'を入力してくださいERROR

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

だから何の問題があるし、それを

答えて

4

問題を解決する方法は、お使いのことのように見えるのコードにありますはDataTableではなくDataViewです。

一部のオプション:あなたは、生のデータが必要な場合は、ソーステーブルを取得するために.Tableプロパティを使用し

DataView dv = (DataView)gridView1.DataSource; 

:あなたは同じフィルタを使用したい場合はDataView

キャスト、それを

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

代わりにこれを試してみてください:

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