关于ASP.NET 将数据导出成Excel 的总结[中]

简介:


直接将DataSet 输出成 Excel,这样解决了网格控件只显示分页的部分数据的问题。

Introduction

I did this when I wanted to do a quick export of an entire DataSet (multiple tables) to Excel. I didn't add any additional customization to the fields, but I did want to make sure that dates, boolean, numbers, and text were all formatted correctly.

This code does that.

At some point, I'd like to make a GridView type component that would allow me to detail more about each item. For example, my latest project required me to make a column formatted with a given barcode font ("Free 3 of 9") that required that I put an * before and after the item number. The solution below doesn't make this easy to do, though... So yeah, not perfect. If anyone else has done something like this, let me know :)

For importing Excel to XML, see this post.

NOTE: This method does NOT require Excel to be installed on the Server.

Background

I prefer to see each table in the DataSet to be named.

ds.Tables[ 0].TableName = " Colors ";
ds.Tables[ 1].TableName = " Shapes ";

I changed it to allow you to pass in a List<Table> in case you don't put them in a DataSet. No big deal either way.

Why did I use an XmlTextWriter when I seem to be only using the WriteRaw? I wanted to be able to have it fix any special characters with the "x.WriteString(row[i].ToString());". Note, this still may have problems with certain characters, since I haven't tested it much.

Using the Code

复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Xml;

public void Convert(DataSet ds, string fileName) {
Convert(ds.Tables, fileName);
}
public void Convert(IEnumerable tables, string fileName) {
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = " application/vnd.ms-excel ";
Response.AddHeader( " content-disposition ",
" attachment; filename= " + fileName + " .xls ");

using (XmlTextWriter x = new XmlTextWriter(Response.OutputStream, Encoding.UTF8)) {
int sheetNumber = 0;
x.WriteRaw( " <?xml version=\"1.0\"?><?mso-application progid=\"Excel.Sheet\"?> ");
x.WriteRaw( " <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
x.WriteRaw( " xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
x.WriteRaw( " xmlns:x=\"urn:schemas-microsoft-com:office:excel\"> ");
x.WriteRaw( " <Styles><Style ss:ID='sText'> " +
" <NumberFormat ss:Format='@'/></Style> ");
x.WriteRaw( " <Style ss:ID='sDate'><NumberFormat " +
" ss:Format='[$-409]m/d/yy\\ h:mm\\ AM/PM;@'/> ");
x.WriteRaw( " </Style></Styles> ");
foreach (DataTable dt in tables) {
sheetNumber++;
string sheetName = ! string.IsNullOrEmpty(dt.TableName) ?
dt.TableName : " Sheet " + sheetNumber.ToString();
x.WriteRaw( " <Worksheet ss:Name=' " + sheetName + " '> ");
x.WriteRaw( " <Table> ");
string[] columnTypes = new string[dt.Columns.Count];

for ( int i = 0; i < dt.Columns.Count; i++) {
string colType = dt.Columns[i].DataType.ToString().ToLower();

if (colType.Contains( " datetime ")) {
columnTypes[i] = " DateTime ";
x.WriteRaw( " <Column ss:StyleID='sDate'/> ");

} else if (colType.Contains( " string ")) {
columnTypes[i] = " String ";
x.WriteRaw( " <Column ss:StyleID='sText'/> ");

} else {
x.WriteRaw( " <Column /> ");

if (colType.Contains( " boolean ")) {
columnTypes[i] = " Boolean ";
} else {
// default is some kind of number.
columnTypes[i] = " Number ";
}

}
}
// column headers
x.WriteRaw( " <Row> ");
foreach (DataColumn col in dt.Columns) {
x.WriteRaw( " <Cell ss:StyleID='sText'><Data ss:Type='String'> ");
x.WriteRaw(col.ColumnName);
x.WriteRaw( " </Data></Cell> ");
}
x.WriteRaw( " </Row> ");
// data
bool missedNullColumn = false;
foreach (DataRow row in dt.Rows) {
x.WriteRaw( " <Row> ");
for ( int i = 0; i < dt.Columns.Count; i++) {
if (!row.IsNull(i)) {
if (missedNullColumn) {
int displayIndex = i + 1;
x.WriteRaw( " <Cell ss:Index=' " + displayIndex.ToString() +
" '><Data ss:Type=' " +
columnTypes[i] + " '> ");
missedNullColumn = false;
} else {
x.WriteRaw( " <Cell><Data ss:Type=' " +
columnTypes[i] + " '> ");
}

switch (columnTypes[i]) {
case " DateTime ":
x.WriteRaw(((DateTime)row[i]).ToString( " s "));
break;
case " Boolean ":
x.WriteRaw((( bool)row[i]) ? " 1 " : " 0 ");
break;
case " String ":
x.WriteString(row[i].ToString());
break;
default:
x.WriteString(row[i].ToString());
break;
}

x.WriteRaw( " </Data></Cell> ");
} else {
missedNullColumn = true;
}
}
x.WriteRaw( " </Row> ");
}
x.WriteRaw( " </Table></Worksheet> ");
}
x.WriteRaw( " </Workbook> ");
}
Response.End();
}



本文转自钢钢博客园博客,原文链接:http://www.cnblogs.com/xugang/archive/2011/09/26/2191649.html,如需转载请自行联系原作者
相关文章
|
4月前
|
关系型数据库 MySQL Shell
不通过navicat工具怎么把查询数据导出到excel表中
不通过navicat工具怎么把查询数据导出到excel表中
52 0
|
28天前
|
前端开发
实现Excel文件和其他文件导出为压缩包,并导入
实现Excel文件和其他文件导出为压缩包,并导入
29 1
|
1月前
|
数据格式 UED
记录一次NPOI库导出Excel遇到的小问题解决方案
【11月更文挑战第16天】本文记录了使用 NPOI 库导出 Excel 过程中遇到的三个主要问题及其解决方案:单元格数据格式错误、日期格式不正确以及合并单元格边框缺失。通过自定义单元格样式、设置数据格式和手动添加边框,有效解决了这些问题,提升了导出文件的质量和用户体验。
170 3
|
1月前
|
Java API Apache
|
1月前
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
57 4
|
2月前
|
JavaScript 前端开发 数据处理
Vue导出el-table表格为Excel文件的两种方式
Vue导出el-table表格为Excel文件的两种方式
101 6
|
3月前
|
SQL C# 数据库
EPPlus库的安装和使用 C# 中 Excel的导入和导出
本文介绍了如何使用EPPlus库在C#中实现Excel的导入和导出功能。首先,通过NuGet包管理器安装EPPlus库,然后提供了将DataGridView数据导出到Excel的步骤和代码示例,包括将DataGridView转换为DataTable和使用EPPlus将DataTable导出为Excel文件。接着,介绍了如何将Excel数据导入到数据库中,包括读取Excel文件、解析数据、执行SQL插入操作。
EPPlus库的安装和使用 C# 中 Excel的导入和导出
|
2月前
|
easyexcel Java UED
SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
在SpringBoot环境中,为了优化大量数据的Excel导出体验,可采用异步方式处理。具体做法是将数据拆分后利用`CompletableFuture`与`ThreadPoolTaskExecutor`并行导出,并使用EasyExcel生成多个Excel文件,最终将其压缩成ZIP文件供下载。此方案提升了导出效率,改善了用户体验。代码示例展示了如何实现这一过程,包括多线程处理、模板导出及资源清理等关键步骤。
|
2月前
|
前端开发 JavaScript
💥【exceljs】纯前端如何实现Excel导出下载和上传解析?
本文介绍了用于处理Excel文件的库——ExcelJS,相较于SheetJS,ExcelJS支持更高级的样式自定义且易于使用。表格对比显示,ExcelJS在样式设置、内存效率及流式操作方面更具优势。主要适用于Node.js环境,也支持浏览器端使用。文中详细展示了如何利用ExcelJS实现前端的Excel导出下载和上传解析功能,并提供了示例代码。此外,还提供了在线调试的仓库链接和运行命令,方便读者实践。
430 5
|
2月前
|
前端开发 JavaScript API
前端基于XLSX实现数据导出到Excel表格,以及提示“文件已经被损坏,无法打开”的解决方法
前端基于XLSX实现数据导出到Excel表格,以及提示“文件已经被损坏,无法打开”的解决方法
203 0