简单易用的导出文件(Excel、word等各种格式)的方法

以前学习过NPOI导出数据到Excel中,代码较长,不易记忆。工作中,看到了其他同事写的代码,研究了一下,贴出来,共同学习。

使用这种方式,不仅可以设置表格的样式,而且代码简洁。

首先,在后台中通过StringBulider拼接一个完整的html标签(StringBulider sbHtml),其中包括表格<table>以及<tr>、<td>和完整的数据;

接下来就是通过输出流输出了,代码如下:

byte[] content = System.Text.Encoding.Default.GetBytes(sbHtml.tostring());//将string转为二进制字节数组
HttpResponse clsreponse = System.Web.HttpContext.Current.Response;
clsreponse.ClearHeaders(); //每次清空之前的
clsreponse.ClearContent();
clsreponse.AddHeader("Content-Disposition", "attachment;filename=TZSJFX" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//xls

clsreponse.ContentType = "application/msexcel";//设置流的输出格式 (输出流的格式有多种,参见网址:http://de.selfhtml.org/diverses/mimetypen.htm

clsreponse.OutputStream.Write(content, 0, content.Length);//输出
clsreponse.End();

结果如下:

PS: 这个输出的是Excel形式的,如果想输出word或其他格式,只需要改动后缀名和ContentType的值。

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我是一只爱积累的小蜗牛,慢慢积累,慢慢进步。

原文地址:https://www.cnblogs.com/janneystory/p/3198355.html