C# WinForm DataTable或DataGridView导出EXCEL
DataTable导出EXCEL
//建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = false; excel.SaveWorkspace(path);//FilePath //生成字段名称 for (int i = 0; i < dt.Columns.Count; i++) { excel.Cells[1, i + 1] = dt.Columns[i].ColumnName; } //填充数据 for (int row = 0; row <= dt.Rows.Count - 1; row++) { for (int column = 0; column < dt.Columns.Count; column++) { if (dt.Rows[row][column].GetType() == typeof(string)) { excel.Cells[row + 2, column + 1] = "'" + dt.Rows[row][column].ToString(); } else { excel.Cells[row + 2, column + 1] = dt.Rows[row][column].ToString(); } }
DataGridView导出EXCEL
同上类似,取值方式不一样 DataTable是 dt.Rows[][] DataGridView是 dt[][]