WebAPI导出CSV
一、JS脚本
window.open("../Ticket/ExportTicket");
二、后台实现代码
[HttpGet]
public ActionResult ExportTicket(TicketSearch search)
{
if (search != null)
{
search.CurrentPage = 1;
search.PageSize = 0;
}
string[] lstTitles = new string[] { "编号", "标题"};
int TotalCount = 0;
List<TicketData> lstTicketData = ListTicketEntityToData(search, out TotalCount);
List<string[]> lstData = new List<string[]>();
foreach (TicketData itemData in lstTicketData)
{
string[] data = new string[]
{
itemData.Barcode,
itemData.Label,
itemData.SiteId.ToString(),
Helper.Htmlhelper.GetSiteInfo(itemData.SiteId),
itemData.Owner,
string.IsNullOrEmpty(itemData.CardId) ? "" : itemData.CardId,
itemData.StartDate == null ? "" : itemData.StartDate.Value.ToString("yyyy-MM-dd HH:mm"),
itemData.EndDate == null ? "" : itemData.EndDate.Value.ToString("yyyy-MM-dd HH:mm"),
itemData.IsValid.ToString(),
itemData.IsUsed.ToString(),
itemData.CreateTime.ToString("yyyy-MM-dd HH:mm")
};
lstData.Add(data);
}
string ExportFileName = Helper.ImportExport.ExportData(lstTitles, lstData);
return File(new System.IO.FileStream(ExportFileName, System.IO.FileMode.Open), "application/octet-stream", "Ticket" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv");
}
public static string ExportData(string[] lstTitles, List<string[]> lstData)
{
try
{
lock (RunningExport)
{
string TemplatePath = AppDomain.CurrentDomain.BaseDirectory + "Export";
string FullFileName = AppDomain.CurrentDomain.BaseDirectory + "Export\\template.csv";
if (Directory.Exists(TemplatePath))
{
if (File.Exists(FullFileName))
File.Delete(FullFileName);
}
else
{
Directory.CreateDirectory(TemplatePath);
}
if (lstTitles.Length <= 0)
{
return null;
}
FileStream fs = new FileStream(FullFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
string data = "";
foreach (string itemTitle in lstTitles)
{
data += itemTitle + ",";
}
sw.WriteLine(data.TrimEnd(','));
foreach (string[] itemData in lstData)
{
data = "";
foreach (string itemChildData in itemData)
{
data += itemChildData + ",";
}
sw.WriteLine(data.TrimEnd(','));
}
sw.Close();
fs.Close();
return FullFileName;
}
}
catch (Exception)
{
return null;
}
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16048927.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。