迭代通过datagrid行导出到Excel(再次)

我正在尝试将dataGrid行导出到Excel工作表。 因为我从一个WinForms(dataGridView)切换到WPF(dataGrid),基本上我不知道WPF到目前为止,我需要你的帮助。

也许有人可以告诉我如何改变我的循环或我必须做的,而不是让行填充到Excel工作表的单元格。

我已阅读所有关于这个问题的文章,但似乎没有find适合我的问题的话题。

这是我填写列名所做的,完美的作品:

for (int i = 1; i < dataGrid.Columns.Count + 1; i++) { Excel.Range BackgroundColor; BackgroundColor = xlWorkSheet.get_Range("a9", "j9"); BackgroundColor.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.RoyalBlue); AxlEx.Cells[9, i] = dataGrid.Columns[i - 1].Header; } 

当它涉及到填充行的单元格时,我尝试了很多尝试,以使其工作

 for (int i = 0; i < dataGrid.Items.Count; i++) { DataRowView aux = (DataRowView)dataGrid.Items[i]; for (int j = 0; j < aux.Row.ItemArray.Length; j++) { //Console.WriteLine(string.Format("{0}-{1}", j, aux.Row.ItemArray[j])); AxlEx.Cells[i + 10, j + 1] = aux.Row.ItemArray[j]; } } 

抛出一个System.InvalidCastexception的types不匹配,这是显而易见的exception……但我不知道如何转换,这里也是拟合主题上没有一个例子,我可以理解改变我的代码。

之前我有这个:

 for (int i = 0; i < dataGrid.Items.Count; i++) { for (int j = 0; j < dataGrid.Columns.Count; j++) { AxlEx.Cells[i + 10, j + 1] = dataRow.Row.ItemArray[j].ToString(); } } 

然后如果我指的是1行

 DataRowView dataRow = (DataRowView)dataGrid.SelectedItem; 

我怎样才能使这个工作?

我不知道是否有必要debugging你的代码。 但是,我想显示我的工作代码导出数据从DataGrid MS Excel

将这个工作从UI线程转移到一个ThreadPool是最好的:

  using Excel = Microsoft.Office.Interop.Excel;//add this library Task.Run(() => { // load excel, and create a new workbook Excel.Application excelApp = new Excel.Application(); excelApp.Workbooks.Add(); // single worksheet Excel._Worksheet workSheet = excelApp.ActiveSheet; // column headings for (int i = 0; i < YourDataTable.Columns.Count; i++) { workSheet.Cells[1, (i + 1)] = YourDataTable.Columns[i].ColumnName; } // rows for (int i = 0; i < YourDataTable.Rows.Count; i++) { // to do: format datetime values before printing for (int j = 0; j < YourDataTable.Columns.Count; j++) { workSheet.Cells[(i + 2), (j + 1)] = YourDataTable.Rows[i][j]; } } excelApp.Visible = true; }); 

我发现问题….

 for (int i = 0; i < dataGrid.Items.Count-1; i++) { DataRowView aux = (DataRowView)dataGrid.Items[i]; for (int j = 0; j < aux.Row.ItemArray.Length; j++) { //Console.WriteLine(string.Format("{0}-{1}", j, aux.Row.ItemArray[j])); AxlEx.Cells[i + 10, j + 1] = aux.Row.ItemArray[j]; } } 

我不得不减去(dataGrid.Items.Count-1),因为dataGrid中有一个额外的空白行似乎导致了问题。 可能由于NULL字段的返回值? 数据网格