(转) 数据导出到Excel(或Word)源代码大全

数据导出到Excel(或Word)源代码大全

在日常工作中,大家都习惯Office作为办公软件,因此,在开发软件的时,常常会有把数据导出到Excel等Office软件的需求。在此,收集一些常用的导出文件的源程序,希望给大家带来方便。(不断更新)

一、DataSet数据集内数据转化为Excel

[csharp] view plain copy
  1. // 作用:把DataSet数据集内数据转化为Excel、Word文件   
  2. // 描述:这些关于Excel、Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后   
  3. //       生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之。      
  4. // 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。   
  5. public void DataSetToExcel(DataSet ds,string FileName)   
  6. {   
  7.    try   
  8.    {   
  9.       //Web页面定义   
  10.       //System.Web.UI.Page mypage=new System.Web.UI.Page();   
  11.   
  12.       HttpResponse resp;   
  13.       resp=HttpContext.Current.Response;   
  14.       resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");   
  15.       resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");   
  16.       resp.ContentType="application/ms-excel";   
  17.   
  18.       //变量定义   
  19.       string colHeaders=null;   
  20.       string Is_item=null;   
  21.   
  22.       //显示格式定义////////////////   
  23.   
  24.   
  25.       //文件流操作定义   
  26.       //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);   
  27.       //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));   
  28.   
  29.       StringWriter sfw=new StringWriter();   
  30.       //定义表对象与行对象,同时用DataSet对其值进行初始化   
  31.       System.Data.DataTable dt=ds.Tables[0];   
  32.       DataRow[] myRow=dt.Select();   
  33.       int i=0;   
  34.       int cl=dt.Columns.Count;   
  35.   
  36.       //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符   
  37.       for(i=0;i<cl;i++)   
  38.       {   
  39.          //if(i==(cl-1))  //最后一列,加/n   
  40.          // colHeaders+=dt.Columns[i].Caption.ToString();   
  41.          //else   
  42.          colHeaders+=dt.Columns[i].Caption.ToString()+"/t";   
  43.       }   
  44.       sfw.WriteLine(colHeaders);   
  45.       //sw.WriteLine(colHeaders);   
  46.   
  47.       //逐行处理数据   
  48.       foreach(DataRow row in myRow)   
  49.       {   
  50.          //当前数据写入   
  51.          for(i=0;i<cl;i++)   
  52.          {   
  53.           //if(i==(cl-1))   
  54.           //   Is_item+=row[i].ToString()+"/n";   
  55.           //else   
  56.           Is_item+=row[i].ToString()+"/t";   
  57.          }   
  58.          sfw.WriteLine(Is_item);   
  59.          //sw.WriteLine(Is_item);   
  60.          Is_item=null;   
  61.       }   
  62.       resp.Write(sfw);   
  63.       //resp.Clear();   
  64.       resp.End();   
  65.    }   
  66.    catch(Exception e)   
  67.    {   
  68.       throw e;   
  69.    }   
  70. }  

二、DataSet数据集内数据转化为Excel文件(2)

[csharp] view plain copy
  1. /// ExportFiles 的摘要说明。   
  2. /// 作用:把DataSet数据集内数据转化为Excel文件   
  3. /// 描述:导出Excel文件      
  4. /// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。   
  5. /// </summary>   
  6. public class ExportFiles   
  7. {   
  8.     private string filePath = "";   
  9.     public ExportFiles(string excel_path)   
  10.     {   
  11.         //   
  12.         // TODO: 在此处添加构造函数逻辑   
  13.         //   
  14.         filePath = excel_path;   
  15.     }   
  16.     /// <summary>   
  17.     /// 将指定的Dataset导出到Excel文件   
  18.     /// </summary>   
  19.     /// <param name="dt"></param>   
  20.     /// <returns></returns>   
  21.     public bool ExportToExcel(System.Data.DataSet ds, string ReportName)   
  22.     {   
  23.         if (ds.Tables[0].Rows.Count == 0)   
  24.         {   
  25.             MessageBox.Show("数据集为空");   
  26.         }   
  27.         Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();   
  28.         Workbook xlbook = xlapp.Workbooks.Add(true);   
  29.         Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];   
  30.         Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);   
  31.         range.MergeCells = true;   
  32.         xlapp.ActiveCell.FormulaR1C1 = ReportName;   
  33.         xlapp.ActiveCell.Font.Size = 20;   
  34.         xlapp.ActiveCell.Font.Bold = true;   
  35.         xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;   
  36.         int colIndex = 0;   
  37.         int RowIndex = 2;   
  38.         //开始写入每列的标题   
  39.         foreach (DataColumn dc in ds.Tables[0].Columns)   
  40.         {   
  41.             colIndex++;   
  42.             xlsheet.Cells[RowIndex, colIndex] = dc.Caption;   
  43.         }   
  44.         //开始写入内容   
  45.         int RowCount = ds.Tables[0].Rows.Count;//行数   
  46.         for (int i = 0; i < RowCount; i++)   
  47.         {   
  48.             RowIndex++;   
  49.             int ColCount = ds.Tables[0].Columns.Count;//列数   
  50.             for (colIndex = 1; colIndex <= ColCount; colIndex++)   
  51.             {   
  52.                 xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i, colIndex - 1];   
  53.                 xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;   
  54.             }   
  55.         }   
  56.   
  57.         xlbook.Saved = true;   
  58.         xlbook.SaveCopyAs(filePath);   
  59.         xlapp.Quit();   
  60.         GC.Collect();   
  61.         return true;   
  62.     }   
  63.   
  64.     public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName)   
  65.     {   
  66.         if (ds.Tables[0].Rows.Count == 0)   
  67.         {   
  68.             MessageBox.Show("数据集为空");   
  69.         }   
  70.         string FileName = filePath;   
  71.   
  72.         //System.Data.DataTable dt = new System.Data.DataTable();   
  73.         FileStream objFileStream;   
  74.         StreamWriter objStreamWriter;   
  75.         string strLine = "";   
  76.         objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);   
  77.         objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);   
  78.   
  79.         strLine = ReportName;   
  80.         objStreamWriter.WriteLine(strLine);   
  81.         strLine = "";   
  82.   
  83.         for (int i = 0; i < ds.Tables[0].Columns.Count; i++)   
  84.         {   
  85.             strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + "          " + Convert.ToChar(9);   
  86.         }   
  87.         objStreamWriter.WriteLine(strLine);   
  88.         strLine = "";   
  89.   
  90.         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)   
  91.         {   
  92.             strLine = strLine + (i + 1) + Convert.ToChar(9);   
  93.             for (int j = 1; j < ds.Tables[0].Columns.Count; j++)   
  94.             {   
  95.                 strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9);   
  96.             }   
  97.             objStreamWriter.WriteLine(strLine);   
  98.             strLine = "";   
  99.         }   
  100.         objStreamWriter.Close();   
  101.         objFileStream.Close();   
  102.   
  103.         //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();   
  104.         //Workbook xlbook = xlapp.Workbooks.Add(true);   
  105.         //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];   
  106.         //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);   
  107.         //range.EntireColumn.AutoFit();   
  108.         //xlapp.Quit();   
  109.         return true;   
  110.     }        
  111. }  

 

三、生成XML然后转换成Excel方式

参考资源:http://www.codeproject.com/office/Excel_Export.asp?df=100&forumid=329437&fr=51 (源程序) 优点:  a. 服务端不用安装Excel程序。  b. 支持一定的Excel文件格式设置,比如字体大小、颜色、合并单元格等。  缺点:  a. 与Excel 2000不兼容:由于Excel 2000不支持XML,所以以这种方法生成的Excel文件可能在Excel2000中不兼容(毕竟目前还有不少用户的电脑装的是Excel 2000)。  b. 可能不支持Excel文件页边距的设置;不支持Excel文件横向、纵向的设置;不支持Excel模板;  c. 编程工作量比较大;  d. 生成的文件本质上是XML文件,需要“另存为xls”才能变成真正的Excel文件。  e. 性能是好是坏还不清楚,目前还没真正在项目中用过。希望有用过此方案的朋友能介绍一下这个方案的性能。

四、导出GridView到Excel

[csharp] view plain copy
  1. //导出GridView到Excel中的关键之处   
  2. //用法: ToExcel(GVStaff, TextBox1.Text);   
  3.   
  4. public static void ToExcel(System.Web.UI.Control ctl,string FileName)   
  5. {   
  6.     HttpContext.Current.Response.Charset ="UTF-8";   
  7.     HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;   
  8.     HttpContext.Current.Response.ContentType ="application/ms-excel";   
  9.     HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");   
  10.     ctl.Page.EnableViewState =false;   
  11.     System.IO.StringWriter  tw = new System.IO.StringWriter();   
  12.     HtmlTextWriter hw = new HtmlTextWriter(tw);   
  13.     ctl.RenderControl(hw);   
  14.     HttpContext.Current.Response.Write(tw.ToString());   
  15.     HttpContext.Current.Response.End();   
  16. }           
  17.         
  18. 必须有下面这句!否则不会通过!   
  19. public override void VerifyRenderingInServerForm(Control control)   
  20. {   
  21.     // Confirms that an HtmlForm control is rendered for   
  22. }  

 

五、DataTable导出到Excel

[csharp] view plain copy
  1. using System;   
  2. using Microsoft.Office.Interop.Excel;   
  3. using System.Windows.Forms;   
  4. namespace DongVI   
  5. {   
  6.  /// <summary>   
  7.  /// DataTable导出到Excel   
  8.  /// 整理:dongVi   
  9.  /// </summary>   
  10.  public class DataTableToExcel   
  11.  {   
  12.   private DataTableToExcel()   
  13.   {   
  14.   
  15.   }   
  16.   /// <summary>   
  17.   /// 导出Excel   
  18.   /// </summary>   
  19.   /// <param name="dt">要导出的DataTable</param>   
  20.   public static void ExportToExcel(System.Data.DataTable dt )   
  21.   {   
  22.    if (dt == null) return;   
  23.       
  24.    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();   
  25.    if (xlApp == null)   
  26.    {   
  27.     // lblMsg.Text = "无法创建Excel对象,可能您的电脑未安装Excel";   
  28.     MessageBox.Show( "无法创建Excel对象,可能您的电脑未安装Excel" );   
  29.     return;   
  30.    }   
  31.    System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();   
  32.    saveDia.Filter = "Excel|*.xls";   
  33.    saveDia.Title = "导出为Excel文件";   
  34.    if(saveDia.ShowDialog()== System.Windows.Forms.DialogResult.OK   
  35.     && !string.Empty.Equals(saveDia.FileName))   
  36.    {   
  37.     Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;   
  38.     Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);   
  39.     Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1   
  40.     Microsoft.Office.Interop.Excel.Range range = null;   
  41.     long totalCount = dt.Rows.Count;   
  42.     long rowRead = 0;   
  43.     float percent = 0;   
  44.     string fileName = saveDia.FileName;   
  45.     //写入标题   
  46.     for (int i = 0; i < dt.Columns.Count; i++)   
  47.     {   
  48.      worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;   
  49.      range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];   
  50.      //range.Interior.ColorIndex = 15;//背景颜色   
  51.      range.Font.Bold = true;//粗体   
  52.      range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中   
  53.      //加边框   
  54.      range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);   
  55.      //range.ColumnWidth = 4.63;//设置列宽   
  56.      //range.EntireColumn.AutoFit();//自动调整列宽   
  57.      //r1.EntireRow.AutoFit();//自动调整行高   
  58.     }   
  59.     //写入内容   
  60.     for (int r = 0; r < dt.DefaultView.Count; r++)   
  61.     {   
  62.      for (int i = 0; i < dt.Columns.Count; i++)   
  63.      {   
  64.       worksheet.Cells[r + 2, i + 1] = dt.DefaultView[r][i];   
  65.       range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2, i + 1];   
  66.       range.Font.Size = 9;//字体大小   
  67.       //加边框   
  68.       range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);   
  69.       range.EntireColumn.AutoFit();//自动调整列宽   
  70.      }   
  71.      rowRead++;   
  72.      percent = ((float)(100 * rowRead)) / totalCount;   
  73.      System.Windows.Forms.Application.DoEvents();   
  74.     }   
  75.     range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;   
  76.     if (dt.Columns.Count > 1)   
  77.     {   
  78.      range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;   
  79.     }   
  80.     try   
  81.     {   
  82.      workbook.Saved = true;   
  83.      workbook.SaveCopyAs(fileName);   
  84.     }   
  85.     catch (Exception ex)   
  86.     {   
  87.      //lblMsg.Text = "导出文件时出错,文件可能正被打开!/n" + ex.Message;   
  88.      MessageBox.Show( "导出文件时出错,文件可能正被打开!/n" + ex.Message );   
  89.      return;   
  90.     }   
  91.   
  92.     workbooks.Close();   
  93.     if (xlApp != null)   
  94.     {   
  95.      xlApp.Workbooks.Close();   
  96.      xlApp.Quit();   
  97.      int generation = System.GC.GetGeneration(xlApp);   
  98.      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);   
  99.      xlApp = null;   
  100.      System.GC.Collect(generation);   
  101.     }   
  102.     GC.Collect();//强行销毁   
  103.     #region 强行杀死最近打开的Excel进程   
  104.     System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");   
  105.     System.DateTime startTime = new DateTime();   
  106.     int m, killId = 0;   
  107.     for (m = 0; m < excelProc.Length; m++)   
  108.     {   
  109.      if (startTime < excelProc[m].StartTime)   
  110.      {   
  111.       startTime = excelProc[m].StartTime;   
  112.       killId = m;   
  113.      }   
  114.     }   
  115.     if (excelProc[killId].HasExited == false)   
  116.     {   
  117.      excelProc[killId].Kill();   
  118.     }   
  119.     #endregion   
  120.     MessageBox.Show( "导出成功!" );   
  121.    }   
  122.   }   
  123.  }   
  124. }  

 

六、DataTable导出到excel(2)

[csharp] view plain copy
  1. StringWriter stringWriter = new StringWriter();   
  2. HtmlTextWriter htmlWriter = new HtmlTextWriter( stringWriter );   
  3. DataGrid excel = new DataGrid();   
  4. System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();   
  5. System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();   
  6. System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();   
  7. AlternatingStyle.BackColor = System.Drawing.Color.LightGray;   
  8. headerStyle.BackColor =System.Drawing.Color.LightGray;   
  9. headerStyle.Font.Bold = true;   
  10. headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;   
  11. itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;;    
  12.   
  13. excel.AlternatingItemStyle.MergeWith(AlternatingStyle);   
  14. excel.HeaderStyle.MergeWith(headerStyle);   
  15. excel.ItemStyle.MergeWith(itemStyle);    
  16. excel.GridLines = GridLines.Both;   
  17. excel.HeaderStyle.Font.Bold = true;   
  18. excel.DataSource = dt.DefaultView;//输出DataTable的内容   
  19. excel.DataBind();   
  20. excel.RenderControl(htmlWriter);   
  21.      
  22. string filestr = "d://data//"+filePath;  //filePath是文件的路径   
  23. int pos = filestr.LastIndexOf( "//");   
  24. string file = filestr.Substring(0,pos);   
  25. if( !Directory.Exists( file ) )   
  26. {   
  27.   Directory.CreateDirectory(file);   
  28. }   
  29. System.IO.StreamWriter sw = new StreamWriter(filestr);   
  30. sw.Write(stringWriter.ToString());   
  31. sw.Close();  

 

七、通过SQL直接导出到Excel数据库

[csharp] view plain copy
  1. exec master..xp_cmdshell @# bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout c:/test.xls -c -S"soa" -U"sa" -P"sa" @#  

注意:参数的大小写,另外这种方法写入数据的时候没有标题。

    关于通过SQL读取EXCEL的方法请参见:http://blog.csdn.net/wonsoft/archive/2008/11/16/3312320.aspx

八、用OleDB 把 DataSet 数据导出到 Excel文件里

[csharp] view plain copy
  1. //dt为数据源(数据表)    
  2. //ExcelFileName 为要导出的Excle文件   
  3. //ModelFile为模板文件,该文件与数据源中的表一致。否则数据会导出失败。   
  4. //ModelFile文件里,需要有一张 与 dt.TableName 一致的表,而且字段也要一致。   
  5. //注明:如果不用ModelFile的话,可以用一个空白Excel文件,不过,要去掉下面创建表的注释,让OleDb自己创建一个空白表。   
  6. public static string TableToExcelFile(DataTable dt,string ExcelFileName,string ModelFile)   
  7. {   
  8.     File.Copy(ModelFile,ExcelFileName);  //复制一个空文件,提供写入数据用   
  9.        
  10.     if(File.Exists(ExcelFileName)==false)   
  11.     {   
  12.         return "系统创建临时文件失败,请与系统管理员联系!";   
  13.     }   
  14.   
  15.     if(dt == null)   
  16.     {   
  17.         return "DataTable不能为空";   
  18.     }   
  19.   
  20.     int rows = dt.Rows.Count;   
  21.   
  22.     int cols = dt.Columns.Count;   
  23.     StringBuilder sb;   
  24.     string connString;   
  25.   
  26.     if(rows == 0)   
  27.     {   
  28.         return "没有数据";   
  29.     }   
  30.   
  31.     sb = new StringBuilder();       
  32.     connString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ExcelFileName+";Extended Properties=Excel 8.0;";       
  33.        
  34.     //生成创建表的脚本   
  35.     //----sb.Append("DROP TABLE "+dt.TableName);   
  36.        
  37.     /*  
  38.     sb.Append("CREATE TABLE ");  
  39.     sb.Append(dt.TableName + " ( ");  
  40.     for(int i=0;i<cols;i++)  
  41.     {  
  42.         if(i < cols - 1)  
  43.         sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName));  
  44.         else  
  45.         sb.Append(string.Format("{0} varchar)",dt.Columns[i].ColumnName));  
  46.     }      
  47.     */   
  48.        
  49.     //return sb.ToString();   
  50.   
  51.     OleDbConnection objConn = new OleDbConnection(connString);   
  52.     OleDbCommand objCmd = new OleDbCommand();   
  53.     objCmd.Connection = objConn;   
  54.     //objCmd.CommandText=sb.ToString();   
  55.   
  56.     try   
  57.     {   
  58.         objConn.Open();   
  59.         //objCmd.ExecuteNonQuery();   
  60.     }   
  61.     catch(Exception e)   
  62.     {   
  63.         return "在Excel中创建表失败,错误信息:" + e.Message;   
  64.     }   
  65.   
  66.     sb.Remove(0,sb.Length);   
  67.   
  68.     sb.Append("INSERT INTO ");   
  69.     sb.Append(dt.TableName + " ( ");   
  70.   
  71.     for(int i=0;i<cols;i++)   
  72.     {   
  73.         if(i < cols - 1)   
  74.             sb.Append(dt.Columns[i].ColumnName + ",");   
  75.         else   
  76.             sb.Append(dt.Columns[i].ColumnName + ") values (");   
  77.     }   
  78.   
  79.     for(int i=0;i<cols;i++)   
  80.     {   
  81.         if(i < cols - 1)   
  82.             sb.Append("@" + dt.Columns[i].ColumnName + ",");   
  83.         else   
  84.             sb.Append("@" + dt.Columns[i].ColumnName + ")");   
  85.     }   
  86.   
  87.     //建立插入动作的Command   
  88.     objCmd.CommandText = sb.ToString();   
  89.     OleDbParameterCollection param = objCmd.Parameters;   
  90.   
  91.     for(int i=0;i<cols;i++)   
  92.     {   
  93.         param.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, OleDbType.VarChar));   
  94.     }   
  95.   
  96.     //遍历DataTable将数据插入新建的Excel文件中   
  97.     foreach (DataRow row in dt.Rows)   
  98.     {      
  99.         for (int i=0; i<param.Count; i++)   
  100.         {   
  101.             param[i].Value = row[i];   
  102.         }   
  103.   
  104.         objCmd.ExecuteNonQuery();   
  105.     }   
  106.   
  107.     return "数据已成功导入Excel";   
  108. }    
  109. //   Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=754176  

 

九、利用OLEDB,以excel为数据库,把dataset中的数据导入到excel文件中

[csharp] view plain copy
  1. public static void exportToExcelByDataset(string filePath, DataSet ds,XmlNode node)   
  2. {   
  3.     string sqlstr;    
  4.   
  5.     if(fi.Exists)   
  6.     {   
  7.          fi.Delete();   
  8.          //throw new Exception("文件删除失败");       
  9.     }   
  10.     else   
  11.     {   
  12.          fi.Create();   
  13.     }   
  14.       
  15.     string mailto:sqlcon=@%22Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended ProPerties=Excel 8.0;";   
  16.     OleDbConnection olecon = new OleDbConnection(sqlcon);   
  17.     OleDbCommand olecmd = new OleDbCommand();   
  18.     olecmd.Connection = olecon;   
  19.     olecmd.CommandType = CommandType.Text;   
  20.   
  21.     try   
  22.     {   
  23.         olecon.Open();   
  24.                
  25.         XmlNode nodec=node.SelectSingleNode("./Method/ShowField");   
  26.         int ii = 0;   
  27.         sqlstr = "CREATE TABLE sheet1(";   
  28.         foreach(XmlNode xnode in nodec.ChildNodes )   
  29.         {   
  30.            if(ii == nodec.ChildNodes.Count - 1)   
  31.            {   
  32.                if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")   
  33.                {   
  34.                    sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number)";          
  35.                }   
  36.                else   
  37.                {   
  38.                    sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";   
  39.                }   
  40.                // sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";   
  41.            }   
  42.            else   
  43.            {   
  44.                if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")   
  45.                {   
  46.                     sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number,";          
  47.                }   
  48.                else   
  49.                {   
  50.                     sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text,";   
  51.                }   
  52.            }   
  53.            //  sqlstr =sqlstr + xnode.Attributes["displayname"].Value + " text";          
  54.            ii++;   
  55.        }   
  56.        olecmd.CommandText = sqlstr;   
  57.        olecmd.ExecuteNonQuery();   
  58.        for(int i=0;i<ds.Tables[0].Rows.Count;i++)   
  59.        {   
  60.            sqlstr = "INSERT INTO sheet1 VALUES(";   
  61.            int jj=0;   
  62.            foreach(XmlNode inode in nodec.ChildNodes )   
  63.            {   
  64.                 if(jj == nodec.ChildNodes.Count-1)   
  65.                 {   
  66.                     if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")   
  67.                     {   
  68.                          sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + ")" ;     
  69.                     }   
  70.                     else   
  71.                     {   
  72.                          sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "')" ;   
  73.                     }   
  74.                 }   
  75.                 else   
  76.                 {   
  77.                     if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")   
  78.                     {   
  79.                          sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + "," ;   
  80.                     }   
  81.                     else   
  82.                     {   
  83.                          sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "'," ;   
  84.                     }   
  85.                 }   
  86.                 jj++;   
  87.            }   
  88.            olecmd.CommandText = sqlstr;   
  89.            olecmd.ExecuteNonQuery();   
  90.         }     
  91.         MessageBox.Show(@"Excel文件:" + filePath + " 导出成功!");   
  92.     }   
  93.     catch(Exception ex)   
  94.     {   
  95.         MessageBox.Show(ex.Message);   
  96.     }   
  97.     finally   
  98.     {   
  99.         olecmd.Dispose();   
  100.         olecon.Close();   
  101.         olecon.Dispose();   
  102.     }   
  103. }   
  104.   
  105. // 判断对象为空   
  106. private static string isnull(string obj)   
  107. {   
  108.     if(obj.Length >0)   
  109.     {   
  110.      return obj;   
  111.     }   
  112.     else   
  113.     {   
  114.      return "null";   
  115.     }    
  116. }  
原文地址:https://www.cnblogs.com/iDennis/p/5816783.html