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
问题 解决办法
随机推荐
- C之数组
1. 数组的地址就是数组里元素的首地址 2. 数组其实就是一块连续的内存空间 3. 每个元素所占大小取决于数组的类型 4. 所有指针变量在内存中的长度是一样的
- python3 @classmethod 和 @staticmethod 的区别
如果您将某个东西定义为classmethod,这可能是因为您打算从类而不是类实例中调用它. 定义类方法的几种方式: 常规方式 : 需要self隐士传递当前类 ...
- org/springframework/cache/jcache/config/AbstractJCacheConfiguration.class
在使用Spring-MVC环境时 报错: Failed to parse configuration class [org.springframework.cache.aspectj.AspectJ ...
- MLN Alchemy
1. 前言: 本文主要参考Alchemy Tutorial, washington主页上挂出的所有Alchemy项目(包括Alchemy1.0, Alchemy2.0, AlchemyLite)都无法 ...
- AnroidStudio gradle版本和android插件的版本依赖
- .Net WebApi接口之Swagger集成详解
本文详细的介绍了.net从一个新的项目中创建api后集成swagger调试接口的流程! 1.首先我们创建一个MVC项目(VS2012): 2.然后在项目中的Controllers文件夹中添加API接口 ...
- MemCache服务安装配置及windows下修改端口号
简述:memcached 开源的分布式缓存数据系统.高性能的NOSQL Linux 一.环境配置与安装 01.编译准备环境 yum install -y gcc make cmake autoconf ...
- ValueError: row index was 65536, not allowed by .xls format
报错:ValueError: row index was 65536, not allowed by .xls format 读取.xls文件正常,在写.xls文件,pd.to_excel()时候会报 ...
- LeetCode 第 164 场周赛
访问所有点的最小时间 不难看出,从点(x1,y1) 到 (x2,y2) 的步数需要 min(dx,dy),其中 dx = abs(x1-x2),dy = abs(y1-y2) class Soluti ...
- Junit测试类中如何调用Http通信
在使用Junit做测试的时候,有时候需要调用Http通信,无论是request还是response或者是session会话,那么在测试类里该如何调用呢,其实很简单,spring给我们提供了三个类 or ...