时间:2020-12-15 00:46:02 | 栏目:.NET代码 | 点击:次
本文实例讲述了C#将Sql数据保存到Excel文件中的方法,非常有实用价值。分享给大家供大家参考借鉴之用。
具体功能代码如下:
public string ExportExcel( DataSet ds,string saveFileName) { try { if (ds == null) return "数据库为空"; bool fileSaved = false; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { return "无法创建Excel对象,可能您的机子未安装Excel"; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 //写入字段 for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { worksheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName; } //写入数值 for (int r = 0; r < ds.Tables[0].Rows.Count; r++) { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { worksheet.Cells[r + 2, i + 1] = ds.Tables[0].Rows[r][i]; } System.Windows.Forms.Application.DoEvents(); } worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。 if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); fileSaved = true; } catch (Exception ex) { fileSaved = false; MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message); } } else { fileSaved = false; } xlApp.Quit(); GC.Collect();//强行销毁 if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL return "成功保存到Excel"; } catch (Exception ex) { return ex.ToString(); } }
希望本文所述实例对大家C#程序设计有所帮助。