关于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,如需转载请自行联系原作者
相关文章
如何根据Excel某列数据为依据分成一个新的工作表
在处理Excel数据时,我们常需要根据列值将数据分到不同的工作表或文件中。本文通过Python和VBA两种方法实现该操作:使用Python的`pandas`库按年级拆分为多个文件,再通过VBA宏按班级生成新的工作表,帮助高效整理复杂数据。
|
数据采集 数据可视化 数据挖掘
用 Excel+Power Query 做电商数据分析:从 “每天加班整理数据” 到 “一键生成报表” 的配置教程
在电商运营中,数据是增长的关键驱动力。然而,传统的手工数据处理方式效率低下,耗费大量时间且易出错。本文介绍如何利用 Excel 中的 Power Query 工具,自动化完成电商数据的采集、清洗与分析,大幅提升数据处理效率。通过某美妆电商的实战案例,详细拆解从多平台数据整合到可视化报表生成的全流程,帮助电商从业者摆脱繁琐操作,聚焦业务增长,实现数据驱动的高效运营。
|
存储 安全 大数据
网安工程师必看!AiPy解决fscan扫描数据整理难题—多种信息快速分拣+Excel结构化存储方案
作为一名安全测试工程师,分析fscan扫描结果曾是繁琐的手动活:从海量日志中提取开放端口、漏洞信息和主机数据,耗时又易错。但现在,借助AiPy开发的GUI解析工具,只需喝杯奶茶的时间,即可将[PORT]、[SERVICE]、[VULN]、[HOST]等关键信息智能分类,并生成三份清晰的Excel报表。告别手动整理,大幅提升效率!在安全行业,工具党正碾压手动党。掌握AiPy,把时间留给真正的攻防实战!官网链接:https://www.aipyaipy.com,解锁更多用法!
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
2924 10
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
分布式计算 Hadoop 大数据
从Excel到Hadoop:数据规模的进化之路
从Excel到Hadoop:数据规模的进化之路
482 10
|
网络协议 定位技术 网络安全
IPIP.NET-IP地理位置数据
IPIP.NET 是一家专注于 IP 地理位置数据的提供商,基于 BGP/ASN 数据与全球 800+ 网络监测点技术,提供高精度的 IPv4 和 IPv6 定位服务。其核心服务包括地理位置查询、详细地理信息和网络工具等,广泛应用于网络安全、广告营销、CDN 优化等领域。数据覆盖全球,支持多语言,每日更新确保实时性。IPIP.NET 提供 API 接口、离线数据库及多种语言 SDK,方便开发者集成使用。
3238 0
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
976 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
存储 Java easyexcel
招行面试:100万级别数据的Excel,如何秒级导入到数据库?
本文由40岁老架构师尼恩撰写,分享了应对招商银行Java后端面试绝命12题的经验。文章详细介绍了如何通过系统化准备,在面试中展示强大的技术实力。针对百万级数据的Excel导入难题,尼恩推荐使用阿里巴巴开源的EasyExcel框架,并结合高性能分片读取、Disruptor队列缓冲和高并发批量写入的架构方案,实现高效的数据处理。此外,文章还提供了完整的代码示例和配置说明,帮助读者快速掌握相关技能。建议读者参考《尼恩Java面试宝典PDF》进行系统化刷题,提升面试竞争力。关注公众号【技术自由圈】可获取更多技术资源和指导。