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. 数据提交成功后如何避免alert被window.location.reload()影响

    数据提交成功用alert提示,但页面立马就重载了 alert("提交成功!"); window.location.reload(); 如何避免? 方法一: setTimeout 延 ...

  2. Python数据结构之三——dict(字典)

    Python版本:3.6.2  操作系统:Windows  作者:SmallWZQ 知识源于生活.Python也是如此. 提到字典,我首先想到的是数学大师--高斯. 为何想起他呢?这主要是因为高斯算法 ...

  3. Leetcode刷题C#版之Toeplitz Matrix

    题目: Toeplitz Matrix A matrix is Toeplitz if every diagonal from top-left to bottom-right has the sam ...

  4. bzoj 3048[Usaco2013 Jan]Cow Lineup 思想,乱搞 stl

    3048: [Usaco2013 Jan]Cow Lineup Time Limit: 2 Sec  Memory Limit: 128 MBSubmit: 237  Solved: 168[Subm ...

  5. TensorFlow4Delphi

    https://github.com/hartmutdavid/TensorFlow4Delphi

  6. C#标识符

  7. spring cloud熔断监控Hystrix Dashboard和Turbine

    参考: http://blog.csdn.net/ityouknow/article/details/72625646 完整pom <?xml version="1.0" e ...

  8. python基础 数据类型 判断语句

    python 类unix系统默认已经安装或使用源码包./confighuremakemake install python运行方法 通过交互式解释器 [root@room1pc01 ~]# pytho ...

  9. SQL Server查询中对于单列数据','分割的数据进行的拆分操作,集合的每一个行变多行

    1.cross apply cross apply 我们可以把它看作成是inner join 来使用 2.outer apply outer apply我们可以把它看做是left join 来使用 注 ...

  10. U-boot-1.1.4中关于hello_world.srec出错

    make[1]: *** No rule to make target `hello_world.srec', needed by `all'.  Stop. make[1]: Leaving dir ...