Web Api 将DataTable装换成Excel,并通过文件流将其下载
不废话,直接上代码
前端代码
<input type="button" class="layui-btn" value="Test-GetFileFromWebApi" onclick="GetFileFromWebApi(this)" /> <script>
function GetFileFromWebApi() {
location.href = '/api/WorkOrderAPI/GetFileFromWebApi';
}
</script>
接口代码
/// <summary>
/// 从WebAPI下载文件
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public IHttpActionResult GetFileFromWebApi()
{
string filePath = string.Empty;
var browser = String.Empty;
if (System.Web.HttpContext.Current.Request.UserAgent != null)
{
browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
}
string excelFile = string.Empty, DownloadExportPath = "DownloadExport\\";
DataTable dt = new DataTable();//这里根据实际逻辑赋值
KP.Commom.OperationExcel _excel = new KP.Commom.OperationExcel();
string s = _excel.DownloadExport(dt, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + DownloadExportPath + "系统客户.xls", "系统客户", out excelFile);
filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DownloadExportPath, excelFile);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
System.IO.FileStream fileStream = System.IO.File.OpenRead(filePath);
httpResponseMessage.Content = new StreamContent(fileStream);
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = browser.Contains("FIREFOX") ? System.IO.Path.GetFileName(filePath) : System.Web.HttpUtility.UrlEncode(System.IO.Path.GetFileName(filePath))
};
return ResponseMessage(httpResponseMessage);
}
公用方法
/// <summary>
/// DataTable转换Excel并下载到本地“下载”文件夹里
/// </summary>
/// <param name="data">DataTable</param>
/// <param name="sheetName">工作簿名称</param>
/// <returns></returns>
public string DownloadExport(DataTable data, string filePath, string sheetName, out string excelFile)
{
string rMsg = string.Empty;
string _excelFile = string.Empty;
try
{
_excelFile = Path.GetFileName(filePath); //文件名
string strExtenName = string.Empty; //检测是否存在文件夹,若不存在就建立个文件夹
string directoryName = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
} //判断文件是否存在
if (File.Exists(filePath))
{
string strFilePath = Path.GetDirectoryName(filePath);
strExtenName = Path.GetExtension(filePath);
string fullFileName = Path.GetFileName(filePath);
string strSubName = fullFileName.Replace(strExtenName, "");
//获取当前目录与当前文件同类的所有文件集
string[] hasFileList = Directory.GetFiles(strFilePath, strSubName + "*" + strExtenName, SearchOption.AllDirectories);
if (hasFileList.LongLength > )
{
int fileSort = ;
string strFileName = string.Empty;
foreach (string item in hasFileList)
{
string loopFullFileName = Path.GetFileName(item);
strFileName = loopFullFileName.Replace(strExtenName, "");
int strLen = strFileName.Length;
string strleft = strFileName.Substring(strLen - , );
string strright = strFileName.Substring(strLen - , );
int leftIndex = strFileName.IndexOf(strleft);
int rightIndex = strFileName.IndexOf(strright);
//是否包含“()”
if (strleft.IndexOf("(") == && strright.IndexOf(")") == )
{
//是否为文件序号
if (rightIndex - leftIndex == )
{
int sratrSort = ;
//取出序号值
string strSort = strFileName.Substring(leftIndex + , );
int.TryParse(strSort, out sratrSort);
//起始序号从1开始
if (sratrSort > )
{
if (sratrSort >= fileSort)
{
fileSort = sratrSort + ;
}
}
else
{
fileSort = sratrSort + ;
}
}
}
}
_excelFile = strSubName + "(" + fileSort + ")" + strExtenName;
filePath = strFilePath + "\\" + _excelFile;
}
} //创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
int i = , j = , count = ;
#region 设置Excel表格标题
IRow titleInfo = sheet.CreateRow(count);
ICell cellTitle = titleInfo.CreateCell();
cellTitle.SetCellValue(sheetName);
ICellStyle titleStyle = workbook.CreateCellStyle();
titleStyle.Alignment = HorizontalAlignment.Center;//水平对齐
IFont titleFont = workbook.CreateFont();
titleFont.FontHeightInPoints = ;
titleFont.Boldweight = short.MaxValue;//字体加粗
titleStyle.SetFont(titleFont);
cellTitle.CellStyle = titleStyle;
#endregion count = count + ;
#region 表头
IRow headRow = sheet.CreateRow(count);
ICell cellHead = null;
ICellStyle styleHead = workbook.CreateCellStyle();//创建样式对象
styleHead.Alignment = HorizontalAlignment.Center;//水平对齐
styleHead.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
IFont font = workbook.CreateFont(); //创建一个字体样式对象
font.FontName = "宋体"; //和excel里面的字体对应
font.Color = new NPOI.HSSF.Util.HSSFColor.Red().Indexed;//颜色参考NPOI的颜色对照表(替换掉PINK())
font.FontHeightInPoints = ;//字体大小
font.Boldweight = short.MaxValue;//字体加粗
styleHead.SetFont(font); //将字体样式赋给样式对象
sheet.SetColumnWidth(, * );//设置列宽
for (j = ; j < data.Columns.Count; ++j)
{
cellHead = headRow.CreateCell(j);
cellHead.CellStyle = styleHead;
cellHead.SetCellValue(data.Columns[j].ColumnName);
sheet.SetColumnWidth(i, * );
}
#endregion count = count + ;
#region 填充Excel内容
for (i = ; i < data.Rows.Count; ++i)
{
IRow rowBody = sheet.CreateRow(count);
ICell CellBody = null;
ICellStyle bodyStyle = workbook.CreateCellStyle();//创建样式对象
bodyStyle.Alignment = HorizontalAlignment.Center;//水平对齐
bodyStyle.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
IFont fontBody = workbook.CreateFont(); //创建一个字体样式对象
fontBody.FontName = "宋体"; //和excel里面的字体对应
fontBody.Color = new NPOI.HSSF.Util.HSSFColor.Black().Indexed;//颜色参考NPOI的颜色对照表(替换掉PINK())
fontBody.FontHeightInPoints = ;//字体大小
fontBody.Boldweight = short.MinValue;//字体加粗
bodyStyle.SetFont(fontBody); //将字体样式赋给样式对象
for (j = ; j < data.Columns.Count; ++j)
{
CellBody = rowBody.CreateCell(j);
CellBody.CellStyle = bodyStyle;
CellBody.SetCellValue(data.Rows[i][j].ToString());
sheet.SetColumnWidth(i, * );
}
++count;
}
#endregion //合并单元格
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , data.Columns.Count)); //生成文件
FileStream file = new FileStream(filePath, FileMode.Create);
workbook.Write(file); file.Close();
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + (!string.IsNullOrEmpty(_excelFile) ? _excelFile : "DownloadData." + strExtenName));
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.Web.HttpContext.Current.Response.WriteFile(filePath);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
catch (Exception ex)
{
rMsg = "异常:" + ex.Message + " Detail:" + (ex.InnerException != null ? ex.InnerException.ToString() : "");
}
excelFile = _excelFile;
return rMsg;
}
Web Api 将DataTable装换成Excel,并通过文件流将其下载的更多相关文章
- python txt装换成excel
工作中,我们需要经常吧一些导出的数据文件,例如sql查出来的结果装换成excel,用文件发送.这次为大家带上python装换excel的脚本 记得先安装wlwt模块,适用版本,python2-3 #c ...
- 将n行3列的数据dataTable装换成m行7列的dataTable
//思路:新建dataTable,定义需要的列, 先将数据源进行分组,第一重遍历获取所有组,第二重遍历获取某一个组的具体数据public void DataBind() { DateTime time ...
- delphi 怎么将一个文件流转换成字符串(String到流,String到文件,相互转化)
//from http://kingron.myetang.com/zsfunc0d.htm (*// 标题:充分利用pascal字符串类型 说明:和PChar不同,string可以保存# ...
- DataTable数据导出到Excel,并发送到客户端进行下载
本代码实现思路是:页面显示和导出分开,导出的数据和用于页面显示的是同一查询数据方式,所以也是同样的数据,只是在导出数据时从数据库重新捞了一次数据.此导出数据方式会先将数据保存到Excel中,然后将创建 ...
- Vue接收后端传过来excel表格的文件流并下载
题外话:当接收文件流时要确定文件流的类型,但也有例外就是application/octet-stream类型,主要是只用来下载的类型,这个类型简单理解意思就是通用类型类似 var .object.ar ...
- Silverlight日记:字符串装换成Path对象
一,需要动态绑定Path <UserControl x:Class="Secom.Emx2.SL.Common.Controls.EleSafe.Ele.Line" xmln ...
- Java,double类型转换成String,String装换成double型
今天,老师布置了小系统,银行用户管理系统,突然发现自己的基础知识好薄弱,就把这些记录一下, double类型转化string:Double.toString(double doub); String类 ...
- HashMap的key装换成List
Map<String,Object> map = new HashMap<String,Object>(); map.put("a","32332 ...
- mvc 解决StyleBundle中 图片绝对路径 装换成相对路径的问题 CssRewriteUrlTransform
问题 解决办法
随机推荐
- SQL-W3School-高级:SQL FOREIGN KEY 约束
ylbtech-SQL-W3School-高级:SQL FOREIGN KEY 约束 1.返回顶部 1. SQL FOREIGN KEY 约束 一个表中的 FOREIGN KEY 指向另一个表中的 P ...
- Qt编写自定义控件28-颜色滑块面板
一.前言 相比于上一个颜色按钮面板,此控件就要难很多,颜色值有三种表示形式,除了程序员最常用的RGB以外,还有HSB和CMY方式. RGB色彩模式是工业界的一种颜色标准,是通过对红(R).绿(G).蓝 ...
- k8s install kubeadm网络原因访问不了谷哥and gpg: no valid OpenPGP data found. 解决办法
gpg: no valid OpenPGP data found. 解决办法 待做.................................... 卡助在这curl -s https://pa ...
- 安装“Microsoft SQL Server 2014 Management Objects”时报错"Error Writing to file: Microsoft.SqlServer.XEvent.Linq.dll."
问题: 当安装的软件依赖Microsoft SQL Server 2014 Management Objects时,会把这个组件打进安装包里,但是在服务器上安装时却报如下错误: “Error Writ ...
- 解决zabbix中文乱码问题
进入Windows系统控制面板-->外观和个性化-->字体(选择一个字体文件simsun.ttc复制)进入zabbix的web服务器[root@test-zabbix]# cd ~/zab ...
- 【计算机视觉】深度相机(八)--OpenNI及与Kinect for windows SDK的比较
OpenNI(开放自然交互)是一个多语言,跨平台的框架,它定义了编写应用程序,并利用其自然交互的API.OpenNI API由一组可用来编写通用自然交互应用的接口组成.OpenNI的主要目的是要形成一 ...
- redis 获取方式和安装(windows)
Windows redis :https://github.com/MSOpenTech/redis/releases Linux redis :https://github.com/phpredis ...
- XKC's basketball team【线段树查询】
XKC , the captain of the basketball team , is directing a train of nn team members. He makes all mem ...
- java核心技术(第四章)对象与类
4.1 面向对象程序设计概述 每个对象包含对用户公开的特定功能部分和隐藏的实现部分. 4.1.1类 由类构造对象的过程称为创建类的实例. 封装(数据隐藏)是与对象有关的.从形式上看,封装不过是将数据和 ...
- 《xv6 Appendices: PC Hardware and Boot loader》学习笔记
MIT 6.828 Lecture 2的preparation要求阅读<xv6 book>的附录部分,附录包括"PC Hardware"和"The Boot ...