通过按钮点击 使datagridview导出到excel
发布网友
发布时间:2022-04-20 18:41
我来回答
共1个回答
热心网友
时间:2022-04-27 13:31
先获取grid的itemsouces转换Datatable
#region 从DataSet到出到Excel
/**/
/// <summary>
/// 执行导出
/// </summary>
/// <param name="ds">要导出的DataTable </param>
/// <param name="toFileName">要导出到的execl文件路径+文件名</param>ps:如果是c/s程序,那您直接丢一openFileDialog就方便多了
/// <param name="strExcelFileName">导出到的execl的Sheet名</param>
private void doExport(DataTable dt, string toFileName, string strSheetName)
{
Excel.Application excel = new Excel.Application(); //Execl的操作类
//读取保存目标的对象
Excel.Workbook bookDest = excel.Workbooks._Open(toFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);//打开要导出到的Execl文件的工作薄。--ps:关于Missing类在这里的作用,我也不知道...囧
Excel.Worksheet sheetDest = bookDest.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;//给工作薄添加一个Sheet
sheetDest.Name = strSheetName;//自己定义名字O(∩_∩)O哈哈~
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);//这句不写不知道会不会报错
foreach (DataColumn col in dt.Columns)
{
colIndex++;
sheetDest.Cells[1, colIndex] = col.ColumnName;//Execl中的第一列,把DataTable的列名先导进去
}
//导入数据行
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
sheetDest.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
bookDest.Saved = true;
bookDest.Save();
excel.Quit();
excel = null;
GC.Collect();//垃圾回收
}
#endregion