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
问题 解决办法
随机推荐
- Linux学习:Makefile简介及模板
一.基本概念介绍: Makefile 文件就是告诉make命令需要怎么样的去编译和链接程序. 编写Makefile的基本规则: 1.如果这个工程没有编译过,那么我们的所有C文件都要编译并被链接. 2. ...
- linux下mysql下载安装
1.下载地址 https://www.mysql.com/downloads/ 选择community server 点击DOWLOAD 选择版本,当前选择的5.6版本 点击下载mysql-5.6. ...
- 【ARTS】01_26_左耳听风-201900506~201900512
ARTS: Algrothm: leetcode算法题目 Review: 阅读并且点评一篇英文技术文章 Tip/Techni: 学习一个技术技巧 Share: 分享一篇有观点和思考的技术文章 Algo ...
- centos7:ssh免密登陆设置
1.使用root用户登录,进入到目录/root/.ssh 2.执行命令:ssh-keygen -t rsa 一路回车,完成后会在目录/root/.ssh下面生成文件 id_rsa和id_rsa.pub ...
- selenium3 web自动化测试框架 二:页面基础操作、元素定位方法封装、页面操作方法封装
学习目的: 掌握自动化框架中需要的一些基础web操作 正式步骤: 使用title_contains检查页面是否正确 # -*- coding:utf-8 -*- import time from se ...
- django 之(四) --- 级联|截流
登陆注册 登陆注册实现 settings.py # redis配置 CACHES = { "default": { "BACKEND": "djang ...
- Java基础——接口和抽象类
接口(interface) 什么是接口? 接口时抽象方法的合集.接口不可以被直接被实例化. 为什么要使用接口? 为了扩展.Java不支持多继承,但是通过接口就可以实现“多继承” 制定规则.接口就是规则 ...
- Linux上安装Julia-1.1
Julia 在Linux上的安装 浙江大学Julia镜像: 浙江大学Julia镜像 下载1.1版本: wget https://mirrors.zju.edu.cn/julia/releases/v1 ...
- K/3 Cloud 单据关联查询
销售出库单 下推 销售退货单,如何获知他们的关联关系?T_SAL_OUTSTOCKENTRY 是销售出库单分录T_SAL_RETURNSTOCKENTRY 是销售退货单分录T_SAL_RETURNST ...
- 最新 新华网java校招面经 (含整理过的面试题大全)
从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.新华网等10家互联网公司的校招Offer,因为某些自身原因最终选择了新华网.6.7月主要是做系统复习.项目复盘.LeetCo ...