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

来源:互联网 发布:数据迁移整体解决方案 编辑:程序博客网 时间:2024/05/01 09:30
数据导出到Excel(或Word)源代码大全
标签: exceldatasetnulloffice数据库generation
 13988人阅读 评论(15) 收藏 举报
 分类:
 
    

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

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

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

  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.       HttpResponse resp;
  12.       resp=HttpContext.Current.Response;
  13.       resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
  14.       resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
  15.       resp.ContentType="application/ms-excel";
  16.       //变量定义
  17.       string colHeaders=null;
  18.       string Is_item=null;
  19.       //显示格式定义////////////////
  20.       //文件流操作定义
  21.       //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
  22.       //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
  23.       StringWriter sfw=new StringWriter();
  24.       //定义表对象与行对象,同时用DataSet对其值进行初始化
  25.       System.Data.DataTable dt=ds.Tables[0];
  26.       DataRow[] myRow=dt.Select();
  27.       int i=0;
  28.       int cl=dt.Columns.Count;
  29.       //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
  30.       for(i=0;i<cl;i++)
  31.       {
  32.          //if(i==(cl-1))  //最后一列,加/n
  33.          // colHeaders+=dt.Columns[i].Caption.ToString();
  34.          //else
  35.          colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
  36.       }
  37.       sfw.WriteLine(colHeaders);
  38.       //sw.WriteLine(colHeaders);
  39.       //逐行处理数据
  40.       foreach(DataRow row in myRow)
  41.       {
  42.          //当前数据写入
  43.          for(i=0;i<cl;i++)
  44.          {
  45.           //if(i==(cl-1))
  46.           //   Is_item+=row[i].ToString()+"/n";
  47.           //else
  48.           Is_item+=row[i].ToString()+"/t";
  49.          }
  50.          sfw.WriteLine(Is_item);
  51.          //sw.WriteLine(Is_item);
  52.          Is_item=null;
  53.       }
  54.       resp.Write(sfw);
  55.       //resp.Clear();
  56.       resp.End();
  57.    }
  58.    catch(Exception e)
  59.    {
  60.       throw e;
  61.    }
  62. }

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

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

三、生成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

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

五、DataTable导出到Excel

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

六、DataTable导出到excel(2)

  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. excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
  13. excel.HeaderStyle.MergeWith(headerStyle);
  14. excel.ItemStyle.MergeWith(itemStyle); 
  15. excel.GridLines = GridLines.Both;
  16. excel.HeaderStyle.Font.Bold = true;
  17. excel.DataSource = dt.DefaultView;//输出DataTable的内容
  18. excel.DataBind();
  19. excel.RenderControl(htmlWriter);
  20.   
  21. string filestr = "d://data//"+filePath;  //filePath是文件的路径
  22. int pos = filestr.LastIndexOf( "//");
  23. string file = filestr.Substring(0,pos);
  24. if( !Directory.Exists( file ) )
  25. {
  26.   Directory.CreateDirectory(file);
  27. }
  28. System.IO.StreamWriter sw = new StreamWriter(filestr);
  29. sw.Write(stringWriter.ToString());
  30. sw.Close();

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

  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文件里

  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.     if(dt == null)
  15.     {
  16.         return "DataTable不能为空";
  17.     }
  18.     int rows = dt.Rows.Count;
  19.     int cols = dt.Columns.Count;
  20.     StringBuilder sb;
  21.     string connString;
  22.     if(rows == 0)
  23.     {
  24.         return "没有数据";
  25.     }
  26.     sb = new StringBuilder();    
  27.     connString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ExcelFileName+";Extended Properties=Excel 8.0;";    
  28.     
  29.     //生成创建表的脚本
  30.     //----sb.Append("DROP TABLE "+dt.TableName);
  31.     
  32.     /*
  33.     sb.Append("CREATE TABLE ");
  34.     sb.Append(dt.TableName + " ( ");
  35.     for(int i=0;i<cols;i++)
  36.     {
  37.         if(i < cols - 1)
  38.         sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName));
  39.         else
  40.         sb.Append(string.Format("{0} varchar)",dt.Columns[i].ColumnName));
  41.     }    
  42.     */
  43.     
  44.     //return sb.ToString();
  45.     OleDbConnection objConn = new OleDbConnection(connString);
  46.     OleDbCommand objCmd = new OleDbCommand();
  47.     objCmd.Connection = objConn;
  48.     //objCmd.CommandText=sb.ToString();
  49.     try
  50.     {
  51.         objConn.Open();
  52.         //objCmd.ExecuteNonQuery();
  53.     }
  54.     catch(Exception e)
  55.     {
  56.         return "在Excel中创建表失败,错误信息:" + e.Message;
  57.     }
  58.     sb.Remove(0,sb.Length);
  59.     sb.Append("INSERT INTO ");
  60.     sb.Append(dt.TableName + " ( ");
  61.     for(int i=0;i<cols;i++)
  62.     {
  63.         if(i < cols - 1)
  64.             sb.Append(dt.Columns[i].ColumnName + ",");
  65.         else
  66.             sb.Append(dt.Columns[i].ColumnName + ") values (");
  67.     }
  68.     for(int i=0;i<cols;i++)
  69.     {
  70.         if(i < cols - 1)
  71.             sb.Append("@" + dt.Columns[i].ColumnName + ",");
  72.         else
  73.             sb.Append("@" + dt.Columns[i].ColumnName + ")");
  74.     }
  75.     //建立插入动作的Command
  76.     objCmd.CommandText = sb.ToString();
  77.     OleDbParameterCollection param = objCmd.Parameters;
  78.     for(int i=0;i<cols;i++)
  79.     {
  80.         param.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, OleDbType.VarChar));
  81.     }
  82.     //遍历DataTable将数据插入新建的Excel文件中
  83.     foreach (DataRow row in dt.Rows)
  84.     {   
  85.         for (int i=0; i<param.Count; i++)
  86.         {
  87.             param[i].Value = row[i];
  88.         }
  89.         objCmd.ExecuteNonQuery();
  90.     }
  91.     return "数据已成功导入Excel";
  92. //   Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=754176

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

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

鸣谢:感谢各位作者的无私奉献!世界有你们真精彩。

0 0
原创粉丝点击