Web Api 将DataTable装换成Excel,并通过文件流将其下载

不废话,直接上代码网址:yii666.com

前端代码文章来源地址https://www.yii666.com/article/758281.html网址:yii666.com<

<input type="button" class="layui-btn" value="Test-GetFileFromWebApi" onclick="GetFileFromWebApi(this)" />

<script>
function GetFileFromWebApi() {
location.href = '/api/WorkOrderAPI/GetFileFromWebApi';
}
</script>

接口代码文章来源地址:https://www.yii666.com/article/758281.html

        /// <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);
}

公用方法文章地址https://www.yii666.com/article/758281.html

        /// <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,并通过文件流将其下载-相关文章

  1. Java,double类型转换成String,String装换成double型

  2. 将n行3列的数据dataTable装换成m行7列的dataTable

  3. js将时间戳装换成日期格式

  4. Web Api 将DataTable装换成Excel,并通过文件流将其下载

  5. js 一数组分割成若干个数组,并装换成字符串赋个li标签

  6. [CSAPP笔记]Binary , Unsigned , Signed 之间的相互装换

  7. 转:js小技巧 ,将彻底屏蔽鼠标右键,可用于Table ,取消选取、防止复制,IE地址栏前换成自己的图标

    1. oncontextmenu=\\\"window.event.returnValue=false\\\" 将彻底屏蔽鼠标右键table border oncontextmenu=return(false)tdno/table 可用于Table2. body onselectstart=\\\"return false\\\" 取消选取、防止复制3. onpaste=\\\"return false\\\" 不准粘贴4. oncopy=\\\"return false;\\\" oncut=\\\"return false;\\\" 防止复制5. link rel=\\\"Shortcut Icon\\\" href=\\\"favicon.ico\\\" IE地址栏前

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png