- ·上一篇:excel如何用快捷筛选
- ·下一篇:excel如何单元格可以拆分
EXCEL和sw如何画凸轮
1.C#如何实现datagridview写入excel
导出数据为Excel文件在开发项目时比较常见的一种需求 。
以前对于数据量较小的情况使用 Microsoft.Office.Interop.Excel.Workbooks相关类,编写起来也比较麻烦,对于数据量较大的情况,在此与大家共享使用SteamWriter类输出Excel文件的方法。经过具体测试,通过在程序中使用多线程配置该方法,导出300000行+17列的约130M的数据需要31秒左右。
[csharp] view plaincopyprint? 1. ///
3. /// 4. /// 5. public static string ExportToExcel(System.Data.DataTable dt, string path) 6. { 7. KillSpecialExcel(); 8. string result = string.Empty; 9. try 10. { 11. // 实例化流对象,以特定的编码向流中写入字符。 12. StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312")); 13. 14. StringBuilder sb = new StringBuilder(); 15. for (int k = 0; k < dt.Columns.Count; k++) 16. { 17. // 添加列名称 18. sb.Append(dt.Columns[k].ColumnName.ToString() + "\t"); 19. } 20. sb.Append(Environment.NewLine); 21. // 添加行数据 22. for (int i = 0; i < dt.Rows.Count; i++) 23. { 24. DataRow row = dt.Rows[i]; 25. for (int j = 0; j < dt.Columns.Count; j++) 26. { 27. // 根据列数追加行数据 28. sb.Append(row[j].ToString() + "\t"); 29. } 30. sb.Append(Environment.NewLine); 31. } 32. sw.Write(sb.ToString()); 33. sw.Flush(); 34. sw.Close(); 35. sw.Dispose(); 36. 37. // 导出成功后打开 38. //System.Diagnostics.Process.Start(path); 39. } 40. catch (Exception) 41. { 42. result = "请保存或关闭可能已打开的Excel文件"; 43. } 44. finally 45. { 46. dt.Dispose(); 47. } 48. return result; 49.} 50.///
2.如何通过aspx页面生成excel
前台代码:
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
<br />
<asp:Button ID="btnExportToExcel" runat="server"
Text="导出数据到Excel" />
后台代码:
/// <summary>
/// 将GridView的数据输出到Excel文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0)
{
return;
}
Response.ClearContent();
Response.ContentEncoding = Encoding.Default;
Response.AddHeader("content-disposition", "attatchment;filename=" + HttpUtility.UrlEncode("我的Excel.xls", Encoding.UTF8));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
//必须重载此方法,以便支持上面的导出操作
public override void (Control control)
{
}
