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
问题 解决办法
随机推荐
- Swift 循环
循环类型 Swift 语言提供了以下几种循环类型.点击链接查看每个类型的详细描述: 循环类型 描述 for-in 遍历一个集合里面的所有元素,例如由数字表示的区间.数组中的元素.字符串中的字符. fo ...
- php判断为空就插入,判断不为空就更新
if ($_GET['tplname']!==null) { if ($userinfo[0] == ''){$exec="INSERT INTO cblej_company_pc_temp ...
- MongoDB安装成windows 服务
观看本文之间,请先移步至下面纠正部分 之前按照MongoDB官网提供的安装方法一直出错 http://cn.docs.mongodb.org/master/tutorial/install-mongo ...
- python中关于with以及contextlib的使用
一般在coding时,经常使用with来打开文件进行文件处理,然后无需执行close方法进行文件关闭. with open('test.py','r' as f: print(f.readline() ...
- PAT 甲级 1017 Queueing at Bank (25 分)(模拟题,有点思维小技巧,第二次做才理清思路)
1017 Queueing at Bank (25 分) Suppose a bank has K windows open for service. There is a yellow line ...
- iOS Xib布局某些控件显示或隐藏<约束的修改>
对于这个问题使用Masonry是很好解决的. 注意:绿色的是label2,当indexpath.section % 2 == 0时,label2不存在. 关键代码如下: if (indexPath.s ...
- unity3d 嵌入iOS的 In App Purchase 应用程序内购买
Unity做东西是快,但是有些功能是需要额外开发的,比如 IAP (In App Purchase,应用程序内购买) 还好unity提供了灵活的扩展功能,允许嵌入原生代码来做一些unity未实现的功能 ...
- MySQL问题:Access denied for user 'mysql'@'localhost'
deep@deep-PC:~$ sudo mysql -uroot -p mysql> update mysql.user set authentication_string=PASSWORD( ...
- js 数组遍历 对象遍历
一.数组遍历 1,普通for循环,经常用的数组遍历 var arr = [1,2,0,3,9]; for ( var i = 0; i <arr.length; i++){ console.lo ...
- MemCache可视化客户端管理及监控工具TreeNMS
参考地址:https://www.cnblogs.com/li150dan/p/9529054.html