最近在做一个报表系统的时候,需要把DATASET中的数据导到EXCEL当中,于是在网上找了一遍,发现了好几种方法,本来以为应该差不多,但后来经过一一试用后,发现在性能上真的差别很大,现在就介绍一下,同时有不对的希望可以指正:
 
1. 原理:利用office组件把dataset中的数据填充到excel文件当中。
这里我不贴出全部代码了,只把关键部分贴出来:
         ///<summary>
         ///方法,导出C1TrueDBGrid中的数据到Excel文件
         ///</summary>
         ///<param name="c1grid">C1TrueDBGrid</param>
         ///<param name="FileName">Excel文件名</param>
         public void ExportToExcel(C1.Win.C1TrueDBGrid.C1TrueDBGrid c1grid,string FileName)
         {
              if(FileName.Trim() == "") return;            //验证strFileName是否为空或值无效
 
              int rowscount = c1grid.Splits[0].Rows.Count; //定义表格内数据的行数
              int colscount = c1grid.Columns.Count;        //定义表格内数据的列数
 
              //行数必须大于0
              if (rowscount <= 0)
              {
                   MessageBox.Show("没有数据可供保存","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                   return;
              }
 
              //列数必须大于0
              if (colscount <= 0)
              {
                   MessageBox.Show("没有数据可供保存","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                   return;
              }
 
              //行数不可以大于65536
              if (rowscount > 65536)
              {
                   MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                   return;
              }
 
              //列数不可以大于255
              if (colscount > 255)
              {
                   MessageBox.Show("数据记录行数太多,不能保存","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                   return;
              }
        
              //将文件保存到工作路径的子目录“/Excel”下,如果路径不存在创建它
              string n_path = Directory.GetCurrentDirectory() + "//Excel";
              if (Directory.Exists(n_path) == false)
              {
                   Directory.CreateDirectory(n_path);
              }
 
              //验证以strFileName命名的文件是否存在,如果存在删除它
              FileInfo fi = new FileInfo(n_path + "//" + FileName + ".xls");
              if(fi.Exists)
              {
                   try
                   {
                       fi.Delete();
                   }
                   catch(Exception fie)
                   {
                       MessageBox.Show(fie.Message,"删除失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                       return;
                   }
              }
        
              Excel.ApplicationClass excel = null;
 
              try
              {
                   //显示进度条
                   KP.PublicForm.ProgressBar pb = new PublicForm.ProgressBar("导出进度");
                   pb.Show();
                   pb.Refresh();
 
                  //新建Excel应用,新建Workbook文件
                   excel = new Excel.ApplicationClass ( ) ;
                   Excel.XlSaveAsAccessMode savemode = new Excel.XlSaveAsAccessMode();
                   excel.Application.Workbooks.Add (true) ;
 
                   //向Excel中写入表格的表头
                   int i = 1;
                   for(int c = 0;c < colscount; c++)
                   {
                       if(c1grid.Splits[0].DisplayColumns[c].Visible)
                       {
                            excel.Cells[1,i] = c1grid.Columns[c].Caption;
                            i++;
                       }
                   }
        
                   //向Excel中逐行逐列写入表格中的数据
                   for(int r = 0; r < rowscount; r++)
                   {
                       Application.DoEvents();
                       pb.SetProgressBarValue(r+1, rowscount);
                       if(pb.Cancel)
                       {
                            break;
                       }
 
                       int j = 1;
                       for(int c = 0;c < colscount; c++)
                       {
                            if(c1grid.Splits[0].DisplayColumns[c].Visible)
                            {
                                 excel.Cells[r + 2,j] = c1grid.Columns[c].CellText(r);
                                 j++;
                            }
                       }
                   }
 
                   //向Excel中写入表格的脚
                   if(c1grid.ColumnFooters)
                   {
                       int col = 1;
                       for(int c = 0;c < colscount; c++)
                       {
                            if(c1grid.Splits[0].DisplayColumns[c].Visible)
                            {
                                 if(c1grid.Columns[c].FooterText != null && c1grid.Columns[c].FooterText.Trim() != "")
                                 {
                                     excel.Cells[rowscount + 2,col] = c1grid.Columns[c].FooterText;
                                 }
                                 col++;
                            }
                       }
                   }
 
                   //关闭进度条
                   pb.Close();
 
                   //设置Excel的默认保存路径为当前路径下的Excel子文件夹
                   excel.DefaultFilePath = n_path;
 
                   //保存文件
                   excel.ActiveWorkbook.SaveAs(FileName + ".xls",excel.ActiveWorkbook.FileFormat,"","",excel.ActiveWorkbook.ReadOnlyRecommended,excel.ActiveWorkbook.CreateBackup,savemode,excel.ActiveWorkbook.ConflictResolution,false,"","");
        
              }
              catch(Exception e1)
              {
                   MessageBox.Show(e1.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                   return;
              }
              finally
              {
                   //关闭Excel应用
                   if(excel != null) excel.Quit();
              }
              MessageBox.Show(FileName + "导出完毕,在" + Application.StartupPath + "//Excel文件夹下","提示", MessageBoxButtons.OK,MessageBoxIcon.Information);
//       }
 
}
 
       总结:这个方法是可以解决问题,但效率最差,3000条长点的record就用了6分钟,晕~~~~
 
2.   原理:利用office组件,同时把dataset的数据导到Clipboard中,然后通过粘贴到excel中。
         Excel.XlSaveAsAccessMode savemode = new Excel.XlSaveAsAccessMode();
                   xlApp.Application.Workbooks.Add (true) ;
                   xlApp.DefaultFilePath = @"c:/";
                   xlApp.ActiveWorkbook.SaveAs("exportExcel.xls",xlApp.ActiveWorkbook.FileFormat,"","",xlApp.ActiveWorkbook.ReadOnlyRecommended,xlApp.ActiveWorkbook.CreateBackup,savemode,xlApp.ActiveWorkbook.ConflictResolution,false,"","","");
        
             
 
 
                   Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing,
                       oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                       oMissing,oMissing,oMissing);
                  
                   Excel.Worksheet xlWorksheet;
 
      
                   // 循环所有DataTable
                   for( int i=0; i<ds.Tables.Count; i++ )
                   {
                       xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
                       // 以TableName作为新加的Sheet页名。
                       xlWorksheet.Name = ds.Tables[i].TableName;
                       // 取出这个DataTable中的所有值,暂存于stringBuffer中。
                       string stringBuffer = "";
                       //向Excel中写入表格的表头
                       if(node != null)
                       {
                            XmlNode nodec=node.SelectSingleNode("./Method/ShowField");
                            int ii = 1;
                            foreach(XmlNode xnode in nodec.ChildNodes )
                            {
                                 xlApp.Cells[1,ii] =xnode.Attributes["displayname"].Value;                               
                                 ii++;
                            }
                      
                           
                            for( int j=0; j<ds.Tables[i].Rows.Count; j++ )
                            {
                                 for( int k=0; k<ds.Tables[i].Columns.Count; k++ )
                                 {
             
                                     stringBuffer += ds.Tables[i].Rows[j][k].ToString();
                                     if( k < ds.Tables[i].Columns.Count - 1 )
                                          stringBuffer += "/t";
                                 }
                                 stringBuffer += "/n";
                            }
                           
                       }
                       else
                       {
                            int ii = 1;
                            for(int c = 0;c<ds.Tables[i].Columns.Count; c++)
                            {
                                 xlApp.Cells[1,ii] = ds.Tables[i].Columns[c].Caption;
                                 ii++;
                            }
                           
                            for( int j=0; j<ds.Tables[i].Rows.Count; j++ )
                            {
                                 for( int k=0; k<ds.Tables[i].Columns.Count; k++ )
                                 {
             
                                     stringBuffer += ds.Tables[i].Rows[j][k].ToString();
                                     if( k < ds.Tables[i].Columns.Count - 1 )
                                          stringBuffer += "/t";
                                 }
                                 stringBuffer += "/n";
                            }
                       }
 
                       System.Windows.Forms.Clipboard.SetDataObject("");
                       // 将stringBuffer放入剪切板。
                       System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
                       // 选中这个sheet页中的第一个单元格
                       ((Excel.Range)xlWorksheet.Cells[2,1]).Select();
                       // 粘贴!
                       xlWorksheet.Paste(oMissing,oMissing);
                       // 清空系统剪切板。
                       System.Windows.Forms.Clipboard.SetDataObject("");
                  
 
 
                  
                   }
                   // 保存并关闭这个工作簿。
                  
             
 
             
                           
                   xlApp.ActiveWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
                   //                 xlWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
                   System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
                   xlWorkbook = null;
                   MessageBox.Show(@"Excel文件:C:/exportExcel.xls 导出成功!");
              }
              catch(Exception ex)
              {
                   MessageBox.Show(ex.Message);
              }
              finally
              {
                   // 释放...
                   xlApp.Quit();
                   System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                   xlApp = null;
                   GC.Collect();
          }
 
       总结:这个方法比上面的方法性能好点,但还是很不好用,比原来的提高了2倍左右。
 
3. 原理:利用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. string sqlcon=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended ProPerties=Excel 8.0;";
  14. OleDbConnection olecon = new OleDbConnection(sqlcon);
  15. OleDbCommand olecmd = new OleDbCommand();
  16. olecmd.Connection = olecon;
  17. olecmd.CommandType = CommandType.Text;
  18. try
  19. {
  20. olecon.Open();
  21. XmlNode nodec=node.SelectSingleNode("./Method/ShowField");
  22. int ii = 0;
  23. sqlstr = "CREATE TABLE sheet1(";
  24. foreach(XmlNode xnode in nodec.ChildNodes )
  25. {
  26. if(ii == nodec.ChildNodes.Count - 1)
  27. {
  28. if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")
  29. {
  30. sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number)";
  31. }
  32. else
  33. {
  34. sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";
  35. }
  36. //      sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";
  37. }
  38. else
  39. {
  40. if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")
  41. {
  42. sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " number,";
  43. }
  44. else
  45. {
  46. sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text,";
  47. }
  48. }
  49. //     sqlstr =sqlstr + xnode.Attributes["displayname"].Value + " text";
  50. ii++;
  51. }
  52. olecmd.CommandText = sqlstr;
  53. olecmd.ExecuteNonQuery();
  54. for(int i=0;i<ds.Tables[0].Rows.Count;i++)
  55. {
  56. sqlstr = "INSERT INTO sheet1 VALUES(";
  57. int jj=0;
  58. foreach(XmlNode inode in nodec.ChildNodes )
  59. {
  60. if(jj == nodec.ChildNodes.Count-1)
  61. {
  62. if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
  63. {
  64. sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + ")" ;
  65. }
  66. else
  67. {
  68. sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "')" ;
  69. }
  70. }
  71. else
  72. {
  73. if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
  74. {
  75. sqlstr = sqlstr + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString()) + "," ;
  76. }
  77. else
  78. {
  79. sqlstr = sqlstr + "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "'," ;
  80. }
  81. }
  82. jj++;
  83. }
  84. olecmd.CommandText = sqlstr;
  85. olecmd.ExecuteNonQuery();
  86. }
  87. MessageBox.Show(@"Excel文件:" + filePath + " 导出成功!");
  88. }
  89. catch(Exception ex)
  90. {
  91. MessageBox.Show(ex.Message);
  92. }
  93. finally
  94. {
  95. olecmd.Dispose();
  96. olecon.Close();
  97. olecon.Dispose();
  98. }
  99. }
  100. /// <summary>
  101. /// change to string "null" if input is null
  102. /// </summary>
  103. /// <param name="obj"></param>
  104. /// <returns></returns>
  105. private static string isnull(string obj)
  106. {
  107. if(obj.Length >0)
  108. {
  109. return obj;
  110. }
  111. else
  112. {
  113. return "null";
  114. }
  115. }
       总结:这个方法是最好的,速度飞快,比上面两种提高不止10倍,而且关键是不需要用到office组 件,所以我正在用着这种方法,客户也满意。当然这个也有它不好的地方,有时候会受到导入的数据不符的异常困扰,而且为了赶时间,代码写的不好,一句话,能 用但要改进的地方很多:)
      

///2007-03-02

最近发现几个导出到EXCEL的方法,这里先记录下来

4.本示例是用于将ListView中的内容倒入到Excel 与常用的逐单元格写不同的是,本例子采用数据写入到range的方法。该方法效率明显较高

  1. Excel.Application app = new Excel.ApplicationClass();
  2. if( app == null)
  3. {
  4. MessageBox.Show("Excel无法启动");
  5. return;
  6. }
  7. app.Visible = true;
  8. Excel.Workbooks wbs = app.Workbooks;
  9. Excel.Workbook wb = wbs.Add(Missing.Value);
  10. Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
  11. Excel.Range r = ws.get_Range("A1","H1");
  12. object [] objHeader = {"标题1","标题2","标题3","标题4","标题5","标题6","标题7","标题8"};
  13. r.Value = objHeader;
  14. if (lv.Items.Count >0)
  15. {
  16. r = ws.get_Range("A2",Missing.Value);
  17. object [,] objData = new Object[this.lv.Items.Count,8];
  18. foreach(ListViewItem lvi in lv.Items)
  19. {
  20. objData[lvi.Index,0] = lvi.Text;
  21. objData[lvi.Index,1] = lvi.SubItems[1].Text;
  22. objData[lvi.Index,2] = lvi.SubItems[2].Text;
  23. objData[lvi.Index,3] = lvi.SubItems[3].Text;
  24. objData[lvi.Index,4] = lvi.SubItems[4].Text;
  25. objData[lvi.Index,5] = lvi.SubItems[5].Text;
  26. objData[lvi.Index,6] = lvi.SubItems[6].Text;
  27. objData[lvi.Index,7] = lvi.SubItems[7].Text;
  28. }
  29. r = r.get_Resize(lv.Items.Count,8);
  30. r.Value = objData;
  31. r.EntireColumn.AutoFit();
  32. }
  33. app = null;

5.由XML文件导出为EXCEL文件

目录下kfcccer.xml为原始数据XML文件,点击生成后会在同级目录下生成kfcccer.xls文件

页面代码如下:

  1. @ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5. <title>XML转换Excel演示</title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <div>
  11. <asp:Button ID="btnChange" runat="server" Font-Bold="True" Font-Size="18pt" ForeColor="Black"
  12. Height="38px" OnClick="btnChange_Click" Text="开始转换" Width="203px" /></div>
  13. </div>
  14. </form>
  15. </body>
  16. </html>

后台代码:

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.IO;
  12. public partial class _Default : System.Web.UI.Page
  13. {
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. }
  17. protected void btnChange_Click(object sender, EventArgs e)
  18. {
  19. try
  20. {
  21. //要转换的XML文件
  22. string XMLFileName = Path.Combine(Request.PhysicalApplicationPath, "kfcccer.xml");
  23. DataSet dsBook = new DataSet();
  24. dsBook.ReadXml(XMLFileName);
  25. int rows = dsBook.Tables[0].Rows.Count + 1;
  26. int cols = dsBook.Tables[0].Columns.Count;
  27. //将要生成的Excel文件
  28. string ExcelFileName = Path.Combine(Request.PhysicalApplicationPath, "kfcccer.xls");
  29. if (File.Exists(ExcelFileName))
  30. {
  31. File.Delete(ExcelFileName);
  32. }
  33. StreamWriter writer = new StreamWriter(ExcelFileName, false);
  34. writer.WriteLine("<?xml version="1.0"?>");
  35. writer.WriteLine("<?mso-application progid="Excel.Sheet"?>");
  36. writer.WriteLine("<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"");
  37. writer.WriteLine(" xmlns:o="urn:schemas-microsoft-com:office:office"");
  38. writer.WriteLine(" xmlns:x="urn:schemas-microsoft-com:office:excel"");
  39. writer.WriteLine(" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"");
  40. writer.WriteLine(" xmlns:html="http://www.w3.org/TR/REC-html40/">");
  41. writer.WriteLine(" <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">");
  42. writer.WriteLine("  <Author>Automated Report Generator Example</Author>");
  43. writer.WriteLine(string.Format("  <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
  44. writer.WriteLine("  <Company>51aspx.com</Company>");
  45. writer.WriteLine("  <Version>11.6408</Version>");
  46. writer.WriteLine(" </DocumentProperties>");
  47. writer.WriteLine(" <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">");
  48. writer.WriteLine("  <WindowHeight>8955</WindowHeight>");
  49. writer.WriteLine("  <WindowWidth>11355</WindowWidth>");
  50. writer.WriteLine("  <WindowTopX>480</WindowTopX>");
  51. writer.WriteLine("  <WindowTopY>15</WindowTopY>");
  52. writer.WriteLine("  <ProtectStructure>False</ProtectStructure>");
  53. writer.WriteLine("  <ProtectWindows>False</ProtectWindows>");
  54. writer.WriteLine(" </ExcelWorkbook>");
  55. writer.WriteLine(" <Styles>");
  56. writer.WriteLine("  <Style ss:ID="Default" ss:Name="Normal">");
  57. writer.WriteLine("   <Alignment ss:Vertical="Bottom"/>");
  58. writer.WriteLine("   <Borders/>");
  59. writer.WriteLine("   <Font/>");
  60. writer.WriteLine("   <Interior/>");
  61. writer.WriteLine("   <Protection/>");
  62. writer.WriteLine("  </Style>");
  63. writer.WriteLine("  <Style ss:ID="s21">");
  64. writer.WriteLine("   <Alignment ss:Vertical="Bottom" ss:WrapText="1"/>");
  65. writer.WriteLine("  </Style>");
  66. writer.WriteLine(" </Styles>");
  67. writer.WriteLine(" <Worksheet ss:Name="MyReport">");
  68. writer.WriteLine(string.Format("  <Table ss:ExpandedColumnCount="{0}" ss:ExpandedRowCount="{1}" x:FullColumns="1"", cols.ToString(), rows.ToString()));
  69. writer.WriteLine("   x:FullRows="1">");
  70. //生成标题
  71. writer.WriteLine("<Row>");
  72. foreach (DataColumn eachCloumn in dsBook.Tables[0].Columns)
  73. {
  74. writer.Write("<Cell ss:StyleID="s21"><Data ss:Type="String">");
  75. writer.Write(eachCloumn.ColumnName.ToString());
  76. writer.WriteLine("</Data></Cell>");
  77. }
  78. writer.WriteLine("</Row>");
  79. //生成数据记录
  80. foreach (DataRow eachRow in dsBook.Tables[0].Rows)
  81. {
  82. writer.WriteLine("<Row>");
  83. for (int currentRow = 0; currentRow != cols; currentRow++)
  84. {
  85. writer.Write("<Cell ss:StyleID="s21"><Data ss:Type="String">");
  86. writer.Write(eachRow[currentRow].ToString());
  87. writer.WriteLine("</Data></Cell>");
  88. }
  89. writer.WriteLine("</Row>");
  90. }
  91. writer.WriteLine("  </Table>");
  92. writer.WriteLine("  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">");
  93. writer.WriteLine("   <Selected/>");
  94. writer.WriteLine("   <Panes>");
  95. writer.WriteLine("    <Pane>");
  96. writer.WriteLine("     <Number>3</Number>");
  97. writer.WriteLine("     <ActiveRow>1</ActiveRow>");
  98. writer.WriteLine("    </Pane>");
  99. writer.WriteLine("   </Panes>");
  100. writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
  101. writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
  102. writer.WriteLine("  </WorksheetOptions>");
  103. writer.WriteLine(" </Worksheet>");
  104. writer.WriteLine(" <Worksheet ss:Name="Sheet2">");
  105. writer.WriteLine("  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">");
  106. writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
  107. writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
  108. writer.WriteLine("  </WorksheetOptions>");
  109. writer.WriteLine(" </Worksheet>");
  110. writer.WriteLine(" <Worksheet ss:Name="Sheet3">");
  111. writer.WriteLine("  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">");
  112. writer.WriteLine("   <ProtectObjects>False</ProtectObjects>");
  113. writer.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
  114. writer.WriteLine("  </WorksheetOptions>");
  115. writer.WriteLine(" </Worksheet>");
  116. writer.WriteLine("</Workbook>");
  117. writer.Close();
  118. Response.Write("<script language="javascript">" + "alert('" + "转换成功! 转换后的Excel文件名为: kfcccer.xls')" + "</script>");
  119. }
  120. catch (Exception ex)
  121. {
  122. Response.Write("<script language="javascript">" + "alert('" + "操作失败! 出错信息: " + ex.Message + "')" + "</script>");
  123. }
  124. }
  125. }

6.以模版形式导出为EXCEL文件 最近在项目中看到同事的一个导出的解决方案,感觉很不错,以前我如果碰到有些客户要按某些格式把数据导出为EXCEL时,就会感觉很麻烦,有段时间会用水 晶报表导出EXCEL的形式来做,但效果很不好,有些控件会提供对应的方法,但这不是我们这些人所喜欢的,我喜欢能自己编,而不喜欢给人已经封装好的东 西,除非他提供原代码也可以,呵呵。其实这个方案说起来很简单,就是先做好一个EXCEL模版,然后用代码把对应的数据填进去,这样就可以很好的满足客户 的按格式导出的需求,而且还可以让客户来提供模版,这样效果更佳,下面就贴些关键代码:

  1. ApplicationClass oExcel = null;
  2. Workbook wb = null;
  3. Sheets sheets = null;
  4. _Worksheet worksheet = null;
  5. Range range = null;
  6. 。。。
  7. public void showBookingData(DataSet ds)
  8. {
  9. showBrHeard(ds.Tables["BR_HEAD"]);
  10. showReference(ds.Tables["BR_REFERENCE"]);
  11. showBrConta(ds.Tables["BR_CONTAINER"]);
  12. showBrCargo(ds.Tables["BR_CARGO"]);
  13. showBrParties(ds.Tables["BR_PARTIES"]);
  14. showBrLocation(ds.Tables["BR_LOCATION"]);
  15. showBrDoor(ds.Tables["BR_DOOR"]);
  16. }
  17. #region 显示Booking数据
  18. private void showBrHeard(System.Data.DataTable dt)
  19. {
  20. if (dt.Rows.Count > 0)
  21. {
  22. DataRow dRow = dt.Rows[0];
  23. if (bkType != "temp")
  24. {
  25. this.range = this.worksheet.get_Range("A2", Type.Missing);
  26. this.range.Value2 = "'"+dRow["CMC_BR_NUMBER"].ToString();
  27. }
  28. this.range = this.worksheet.get_Range("G2", Type.Missing);
  29. this.range.Value2 = Utility.GetCarrier(dRow["SCAC_CODE"].ToString());
  30. this.range = this.worksheet.get_Range("F11", Type.Missing);
  31. String tfc = dRow["TRAFFIC_MODE"].ToString();
  32. this.range.Value2 = Utility.GetTrafficById(Convert.ToDecimal(tfc));
  33. String drm = dRow["PICKUP_DELIVERY"].ToString();
  34. this.range = this.worksheet.get_Range("H11", Type.Missing);
  35. this.range.Value2 = Utility.GetDragModeById(Convert.ToDecimal(drm)).ToUpper();
  36. if (dRow["VESSEL_NAME"].ToString().Trim().Length != 0)
  37. {
  38. this.range = this.worksheet.get_Range("A23", Type.Missing);
  39. this.range.Value2 = dRow["VESSEL_NAME"].ToString() + "/" + dRow["VESSEL_VOYAGE"].ToString();
  40. }
  41. else
  42. {
  43. if (dRow["EST_DEPARTDATE"].ToString().Trim().Length != 0)
  44. {
  45. this.range = this.worksheet.get_Range("D23", Type.Missing);
  46. this.range.Value2 = Convert.ToDateTime(dRow["EST_DEPARTDATE"]).ToString("yyyy-MM-dd");
  47. }
  48. else if (dRow["EST_ARRIVDATE"].ToString().Trim().Length != 0)
  49. {
  50. this.range = this.worksheet.get_Range("C23", Type.Missing);
  51. this.range.Value2 = Convert.ToDateTime(dRow["EST_ARRIVDATE"]).ToString("yyyy-MM-dd");
  52. }
  53. }
  54. writeStrDate("A", 41, dRow["REMARK"].ToString() + "/n");
  55. if (bkType != "temp")
  56. {
  57. if (dRow["BR_NUMBER"] != null && dRow["BR_NUMBER"].ToString() != "")
  58. {
  59. strRN += "Booking No." + dRow["BR_NUMBER"].ToString() + "/n";
  60. }
  61. }
  62. if (dRow["RATE_REFNO"] != null && dRow["RATE_REFNO"].ToString() != "")
  63. {
  64. strRN += "Contact No." + dRow["RATE_REFNO"].ToString() + "/n";
  65. }
  66. }
  67. }
  68. 。。。。。。

做法简单,但效果很好。唯一缺点就是速度比较慢,而且受限制比较多。

参考地址:http://www.cnblogs.com/kfcccer/archive/2007/05/20/753441.html

7.按XML定义格式把DATASET导出EXCEL    这个方法我没用过,是在CSDN上看到的,主要需求是说在DATESET导出为EXCEL时,需要对其中的数据进行定义,不然导出后与现有格式对不上,比 如时间的,导出后会和原来的数据有出入等等一类的问题.   我感觉其实和第五个比较相近,但因为最近比较忙.我也没时间要验证,如果谁用了希望可以反馈给我,谢谢了.下面是代码:

private static void DataSetExportToExcel(DataSet source, string fileName)

{

System.IO.StreamWriter excelDoc;

excelDoc = new System.IO.StreamWriter(fileName);

const string startExcelXML = @"<xml version> <Workbook " +

"xmlns=/"urn:schemas-microsoft-com:office:spreadsheet/" " +

" xmlns:o=/"urn:schemas-microsoft-com:office:office/"  " +

"xmlns:x=/"urn:schemas-    microsoft-com:office:" +

"excel/"  xmlns:ss=/"urn:schemas-microsoft-com:" +

"office:spreadsheet/">  <Styles>  " +

"<Style ss:ID=/"Default/" ss:Name=/"Normal/">  " +

"<Alignment ss:Vertical=/"Bottom/"/>  <Borders/>" +

"  <Font/>  <Interior/>  <NumberFormat/>" +

"  <Protection/>  </Style>  " +

"<Style ss:ID=/"BoldColumn/">  <Font " +

"x:Family=/"Swiss/" ss:Bold=/"1/"/>  </Style>  " +

"<Style     ss:ID=/"StringLiteral/">  <NumberFormat" +

" ss:Format=/"@/"/>  </Style>  <Style " +

"ss:ID=/"Decimal/">  <NumberFormat " +

"ss:Format=/"0.0000/"/>  </Style>  " +

"<Style ss:ID=/"Integer/">  <NumberFormat " +

"ss:Format=/"0/"/>  </Style>  <Style " +

"ss:ID=/"DateLiteral/">  <NumberFormat " +

"ss:Format=/"mm/dd/yyyy;@/"/>  </Style>  " +

"</Styles>  ";

const string endExcelXML = "</Workbook>";

int rowCount = 0;

int sheetCount = 1;

excelDoc.Write(startExcelXML);

excelDoc.Write("<Worksheet ss:Name=/"Sheet" + sheetCount + "/">");

excelDoc.Write("<Table>");

excelDoc.Write("<Row>");

for (int x = 0; x < source.Tables[0].Columns.Count; x++)

{

excelDoc.Write("<Cell ss:StyleID=/"BoldColumn/"><Data ss:Type=/"String/">");

excelDoc.Write(source.Tables[0].Columns[x].ColumnName);

excelDoc.Write("</Data></Cell>");

}

excelDoc.Write("</Row>");

foreach (DataRow x in source.Tables[0].Rows)

{

rowCount++;

//if the number of rows is > 64000 create a new page to continue output

if (rowCount == 64000)

{

rowCount = 0;

sheetCount++;

excelDoc.Write("</Table>");

excelDoc.Write(" </Worksheet>");

excelDoc.Write("<Worksheet ss:Name=/"Sheet" + sheetCount + "/">");

excelDoc.Write("<Table>");

}

excelDoc.Write("<Row>"); //ID=" + rowCount + "

for (int y = 0; y < source.Tables[0].Columns.Count; y++)

{

System.Type rowType;

rowType = x[y].GetType();

switch (rowType.ToString())

{

case "System.String":

string XMLstring = x[y].ToString();

XMLstring = XMLstring.Trim();

XMLstring = XMLstring.Replace("&", "&");

XMLstring = XMLstring.Replace(">", ">");

XMLstring = XMLstring.Replace("<", "<");

excelDoc.Write("<Cell ss:StyleID=/"StringLiteral/">" +

"<Data ss:Type=/"String/">");

excelDoc.Write(XMLstring);

excelDoc.Write("</Data></Cell>");

break;

case "System.DateTime":

//Excel has a specific Date Format of YYYY-MM-DD followed by

//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000

//The Following Code puts the date stored in XMLDate

//to the format above

DateTime XMLDate = (DateTime)x[y];

string XMLDatetoString = ""; //Excel Converted Date

XMLDatetoString = XMLDate.Year.ToString() +

"-" +

(XMLDate.Month < 10 ? "0" +

XMLDate.Month.ToString() : XMLDate.Month.ToString()) +

"-" +

(XMLDate.Day < 10 ? "0" +

XMLDate.Day.ToString() : XMLDate.Day.ToString()) +

"T" +

(XMLDate.Hour < 10 ? "0" +

XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +

":" +

(XMLDate.Minute < 10 ? "0" +

XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +

":" +

(XMLDate.Second < 10 ? "0" +

XMLDate.Second.ToString() : XMLDate.Second.ToString()) +

".000";

excelDoc.Write("<Cell ss:StyleID=/"DateLiteral/">" +

"<Data ss:Type=/"DateTime/">");

excelDoc.Write(XMLDatetoString);

excelDoc.Write("</Data></Cell>");

break;

case "System.Boolean":

excelDoc.Write("<Cell ss:StyleID=/"StringLiteral/">" +

"<Data ss:Type=/"String/">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.Int16":

case "System.Int32":

case "System.Int64":

case "System.Byte":

excelDoc.Write("<Cell ss:StyleID=/"Integer/">" +

"<Data ss:Type=/"Number/">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.Decimal":

case "System.Double":

excelDoc.Write("<Cell ss:StyleID=/"Decimal/">" +

"<Data ss:Type=/"Number/">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.DBNull":

excelDoc.Write("<Cell ss:StyleID=/"StringLiteral/">" +

"<Data ss:Type=/"String/">");

excelDoc.Write("");

excelDoc.Write("</Data></Cell>");

break;

default:

throw (new Exception(rowType.ToString() + " not handled."));

}

}

excelDoc.Write("</Row>");

}

excelDoc.Write("</Table>");

excelDoc.Write(" </Worksheet>");

excelDoc.Write(endExcelXML);

excelDoc.Close();

}

原文转自:http://blog.csdn.net/simonllf/article/details/1441672

对.NET中导出数据到EXCEL的几种方法探讨的更多相关文章

  1. Delphi 导出数据至Excel的7种方法【转】

    一; delphi 快速导出excel   uses ComObj,clipbrd;   function ToExcel(sfilename:string; ADOQuery:TADOQuery): ...

  2. Delphi 导出数据至Excel的7种方法

    一; delphi 快速导出excel uses ComObj,clipbrd; function ToExcel(sfilename:string; ADOQuery:TADOQuery):bool ...

  3. 【转】asp.net导出数据到Excel的三种方法

    来源:http://www.cnblogs.com/lishengpeng1982/archive/2008/04/03/1135490.html 原文出处:http://blog.csdn.net/ ...

  4. 手把手教你springboot中导出数据到excel中

    手把手教你springboot中导出数据到excel中 问题来源: 前一段时间公司的项目有个导出数据的需求,要求能够实现全部导出也可以多选批量导出(虽然不是我负责的,我自己研究了研究),我们的项目是x ...

  5. .net中从GridView中导出数据到excel(详细)

    1,创建数据源 找到要导出的GridView中的数据. 2,重写VerifyRenderingInServerForm方法. public override void VerifyRenderingI ...

  6. NPOI从数据库中导出数据到Excel

    首先要添加NPOI.dll程序集 https://yunpan.cn/cMeSTELJSXmJJ  访问密码 8d83 把里面的程序集都添加到引用里 下面的代码是从数据库导出到Excel { //pa ...

  7. Java导出数据为EXCEL的两种方式JXL和POI

    JXL和POI导出数据方式的比较 POI支持excel2003和2007,而jxl只支持excel2003. 下面为测试代码: public class TestCondition { /** * 生 ...

  8. Dynamics CRM2016 新功能之从CRM APP中导出数据至EXCEL

    新版的CRM对移动端做了很多的改进,这归咎于微软对APP端的越来越重视.自己装了个IOS版的APP,体验了下基本的功能,比原来好用很多很顺滑,这里要介绍的是一个新的数据导出功能. 咱们进入case列表 ...

  9. mysql导出数据到excel的两种方式

    使用第一种方式如果数据中有换行符的话会自动换行,但使用第二种方式就不会出现这种效果了.两种方式自己选择哈 1:select * from into outfile 'c:/Users/a.xls' t ...

随机推荐

  1. 1011 World Cup Betting (20 分)

    1011 World Cup Betting (20 分) With the 2010 FIFA World Cup running, football fans the world over wer ...

  2. matplot 代码实例2

    要画出如上图(注意原点有边距),怎么办呢? 简单而优雅,请看代码: #!/usr/bin/env python # coding=utf-8 import matplotlib.pyplot as p ...

  3. 初次从eclipse转到intellij idea上的一些经验

    如果出现:mvn 请使用 -source 7 或更高版本以启用 diamond 运算符 这种问题 pom.xml里 <build>标签里面 需要加入这么一段 <plugins> ...

  4. Parallel I/O and Columnar Storage

    Parallel I/O and Columnar Storage We begin with a high level overview of the system while follow up ...

  5. php 编程笔记分享

    php获取POST数据的三种方法php 图片加水印源代码php+ajax+json的一个最简单实例php 汉字转拼音源码php遍历目录,生成目录下每个文件的md5值并写入到结果文件中php实现linu ...

  6. django中视图处理请求方式(FBV、CBV)

    FBV FBV(function base views) 就是在视图里使用函数处理请求. 在之前django的学习中,我们一直使用的是这种方式,所以不再赘述. CBV CBV(class base v ...

  7. NOIP考前复习-数制转换,数论模板与文件读写

    数制转换有两种题型,一般一题,分值1.5分. 题型一:R进制转十进制 解法就是:按权展开,但要注意各个位的权,最低位(最右边)的权是0次方,权值为1. 纯整数的情况: (11010110)2 = 1× ...

  8. C常用问题

    linux系统,gcc编译器包含引用的头文件位置

  9. leetcode118

    public class Solution { public IList<IList<int>> Generate(int numRows) { var list = new ...

  10. VBA 调用DLL动态链接库

    在ArcMap中引用动态链接库       我在VB6下编译生成了一个动态链接库文件VBAPrj.dll,其中有一类模块VBACls,此类模块有一个方法Test(Doc As Object).     ...