0.准备工作

 

1.下载并引入Aspose.Cells

下载Aspose Cells并引入using Aspose.Cells 下面示例中用的是.net 3.0版本的Aspose Cells,编译环境VS2013
具体下载和引入方法见:http://www.cnblogs.com/moonache/p/4991459.html

1.使用Aspose将DataTable转为Excel

 

1.代码

下面代码用于将DataTable dt 转为Excel文件并存在path目录下
/// <summary>
/// DataTable转Excel文件
/// </summary>
/// <param name="dt"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool ExportExcelWithAspose(DataTable dt, string path)
{ if (dt != null)
{
try
{
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[];
//为head添加样式
Aspose.Cells.Style headStyle = workbook.Styles[workbook.Styles.Add()];
//设置居中
headStyle.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
//设置背景颜色
headStyle.ForegroundColor = System.Drawing.Color.FromArgb(, , );
headStyle.Pattern = BackgroundType.Solid;
headStyle.Font.Size = ;
headStyle.Font.Name = "宋体";
headStyle.Font.IsBold = true; //为单元格添加样式
Aspose.Cells.Style cellStyle = workbook.Styles[workbook.Styles.Add()];
//设置居中
cellStyle.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
cellStyle.Pattern = BackgroundType.Solid;
cellStyle.Font.Size = ;
cellStyle.Font.Name = "宋体"; //设置列宽 从0开始 列宽单位是字符
cellSheet.Cells.SetColumnWidth(, );
cellSheet.Cells.SetColumnWidth(, );
cellSheet.Cells.SetColumnWidth(, );
cellSheet.Cells.SetColumnWidth(, );
cellSheet.Cells.SetColumnWidth(, ); int rowIndex = ;
int colIndex = ;
int colCount = dt.Columns.Count;
int rowCount = dt.Rows.Count;
//Head 列名处理
for (int i = ; i < colCount; i++)
{
cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Columns[i].ColumnName);
cellSheet.Cells[rowIndex, colIndex].SetStyle(headStyle);
colIndex++;
}
rowIndex++;
//Cell 其它单元格处理
for (int i = ; i < rowCount; i++)
{
colIndex = ;
for (int j = ; j < colCount; j++)
{
cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Rows[i][j].ToString());
cellSheet.Cells[rowIndex, colIndex].SetStyle(cellStyle);
colIndex++;
}
rowIndex++;
}
cellSheet.AutoFitColumns(); //列宽自动匹配,当列宽过长是收缩
path = Path.GetFullPath(path);
//workbook.Save(path,SaveFormat.CSV);
workbook.Save(path);
return true;
}
catch (Exception e)
{
throw new Exception("导出Excel失败" + e.Message);
}
}
else
{
return false;
} }
下面代码用于直接在页面输出Excel文件,供用户下载
WonderTools.ExportExcelWithAspose(templateDt,filePath);

//提供excel的下载
HttpResponse _Response = HttpContext.Current.Response;
_Response.Clear();
_Response.ClearHeaders();
_Response.Buffer = false;
_Response.ContentType = "application/x-excel";
_Response.AppendHeader("Content-Disposition", "attachment;filename=Template.xlsx");
_Response.WriteFile(fileInfo.FullName);
_Response.Flush();
_Response.End();
 

PPS:

直接通过 ashx 获取数据库中的数据并下载 Excel
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.AddHeader("Content-Disposition",
"attachment;filename=" + context.Server.UrlEncode("数据.xlsx")); using (var dt = SqlHelper.ExecuteQuery("SELECT * FROM T_Users"))
{
var workbook = new Workbook();
var sheet = workbook.Worksheets[]; // Header
for (var i = ; i < dt.Columns.Count; i++)
{
sheet.Cells[, i].PutValue(dt.Columns[i].ColumnName);
}
// Content
for (var i = ; i < dt.Rows.Count; i++)
{
for (var j = ; j < dt.Columns.Count; j++)
{
sheet.Cells[i + , j].PutValue(dt.Rows[i][j].ToString());
}
}
workbook.Save(context.Response.OutputStream,SaveFormat.Xlsx);
}
}

使用Aspose将DataTable转Excel的更多相关文章

  1. NPOI、MyXls、Aspose.Cells 导入导出Excel(转)

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导s出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你 ...

  2. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  3. DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)

    /// <summary> /// DataTable to Excel(将数据表中的数据读取到excel格式内存中) /// </summary> /// <param ...

  4. Aspose 强大的服务器端 excel word ppt pdf 处理工具

    Aspose 强大的服务器端 excel word ppt pdf 处理工具 http://www.aspose.com/java/word-component.aspx

  5. Datatable导出Excel

    ; IRow headerRow = sheet.CreateRow(); ; ; ; iRowIndex++; } ; i < icolIndex; i++) { sheet.AutoSize ...

  6. Aspose.Cells 导入导出EXCEL(转)

    Aspose.Cells 导入导出EXCEL      修改样式        Workbook workbook = new Workbook(); //工作簿          Worksheet ...

  7. ashx导出dataTable为Excel

    一,datatable导出Excel,用户可以选择路径,方法如下: /// <summary> /// DataTable导出到Excel /// </summary> /// ...

  8. c# Datatable导出Excel

    using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; ...

  9. C# DataTable导出EXCEL后身份证、银行卡号等长数字信息显示乱码解决

    在DataTable导出EXCEL后发现有些格式显示有问题,比如身份证.银行卡号等大于11位的数字显示为科学计数法.13681-1等 带中划线的两段数字显示为日期格式等. 处理方法如下: public ...

随机推荐

  1. vuex学习笔记

    一.vuex的目的 把组件的共享状态抽取出来,以一个全局单例模式管理.在这种模式下,组件树构成了一个巨大的视图,不管在树的哪个位置,任何组件都能获取状态或触发行为. 二.vuex集中式管理数据 安装 ...

  2. 解决xshell评估期已过的问题

    问题:时间长没有打开xshell,今天突然打开提示评估期已过,如下图所示: 点击采购会弹出购买的界面,(对于我们这些程序屌怎么会花899购买一款软件)点击取消就会退出. 解决方法: 卸载这个要收费的版 ...

  3. C语言之prinf的用法

    1. n换行字符 1).直接输出内容 printf("哈哈\n"); 2).带参数的输出 int i = 10 ; %d:输入控制符 printf ("%d\n" ...

  4. Websocket原理及使用场景[转载]

    WebSocket的使用场景 社交聊天.弹幕.多玩家游戏.协同编辑.股票基金实时报价.体育实况更新.视频会议/聊天.基于位置的应用.在线教育.智能家居等需要高实时的场景 由轮询到WebSocket 1 ...

  5. 洛谷P1345 [USACO5.4]奶牛的电信Telecowmunication【最小割】分析+题解代码

    洛谷P1345 [USACO5.4]奶牛的电信Telecowmunication[最小割]分析+题解代码 题目描述 农夫约翰的奶牛们喜欢通过电邮保持联系,于是她们建立了一个奶牛电脑网络,以便互相交流. ...

  6. mdb导入SqlServer

    弄了一份医案数据库,打开一看...命名全中文,好吧,导入SQLServer走起 SQL: SELECT * INTO newtable FROM OPENDATASOURCE ('Microsoft. ...

  7. C/C++语言简介之编程开发

    一.编译器 GCC:GNU组织开发的开源免费的编译器. MinGW:Windows操作系统下的GCC. Clang:开源的BSD协议的基于LLVM的编译器. Visual C++:Microsoft ...

  8. 依赖于boodtrap3的插件推荐以及bootrap发展前景

    作为一个栅格系统和速度开发的,偏向于框架,bootstrap出来很火,为了节省效率,不少公司选用这个框架进行开发,一同被发现的是依赖于bootrap各种插件的adminLTE的集成模版,但是前端框架日 ...

  9. 以kaggle-titanic数据为基础的完整的机器学习

    1. 引入所有需要的包 # -*- coding:utf-8 -*- # 忽略警告 import warnings warnings.filterwarnings('ignore') # 引入数据处理 ...

  10. ERROR namenode.NameNode: Failed to start namenode. java.lang.IllegalArgument

    这个问题一般是配置文件配置没有配置好的原因