将表格转换为excel

我想把我的表中的所有logging写入一个excel文件。 我的桌子上有大约30000行。

我可以写20000行只有excel。 System out of memoryexception发生之后。

这是我的代码。 提前致谢。

 using (SqlConnection con = new SqlConnection(strconnection)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_ReportwithoutDup")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Report1"); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=Report1.xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } } } } } 

所以,不是一个完美的解决scheme,但是因为你使用的是一个web框架(asp.net),所以你可以把它全写到一个HTML表格中,然后将响应的内容types设置为application/vnd.ms-excel 。 其结果是浏览器将下载一个客户端在Excel中默认打开的CSV文件。