#region 批量导出
/// <summary>
/// 批量导出
/// </summary>
/// <param name="IDs">IDs集合</param>
/// <param name="type">导出类型(支持多个)</param>
/// <returns></returns>
public ActionResult BatchExport(string IDs, int type)
{
string FileName = string.Empty;
if (type == 2)
FileName = "xxx.html";
else if (type == 3)
FileName = "xxx.html";
else
FileName = "xxx.html";
//时间戳
string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
//项目路径
string RootDir = HttpRuntime.AppDomainAppPath;
//模板文件路径
string FileDir = RootDir + "Template\\";
//临时存放路径
string TempDir = RootDir + "Download\\" + timestamp + "\\";
//Zip存放路径
string ZipDir = RootDir + "Download\\" + timestamp + ".zip";
//创建临时文件夹
if (!Directory.Exists(TempDir))
{
Directory.CreateDirectory(TempDir);
}
//内存流
MemoryStream ms = new MemoryStream();
//获取模板内容
string templateContent = System.IO.File.ReadAllText(FileDir + FileName, System.Text.Encoding.Default);
foreach (var item in IDs.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries))
{
//导出的DOC文件名
string exportFileName = string.Empty;
//填充变量键值对
IDictionary<string, string> dic = new Dictionary<string, string>();
if (type == 2)
dic = SetDic(item, ref exportFileName);
else if (type == 3)
dic=...
else
dic = ...
if (dic == null)
{
continue;
}
//填充后的文本
string content = CommonMethod.ReplaceContent(templateContent, dic);
//HTML文件保存在临时文件夹内
System.IO.File.WriteAllText(TempDir + exportFileName + ".doc", content, System.Text.Encoding.Default);
}
//压缩文件夹(方法见Zip压缩)
ZipDir(TempDir, ZipDir);
//文件推送下载
return File(System.IO.File.ReadAllBytes(ZipDir), "application/octet-stream", timestamp + ".zip");
}
/// <summary>
/// 赋值
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
private IDictionary<string, string> SetDic(string Id, ref string fileName)
{
IDictionary<string, string> dic = new Dictionary<string, string>();
//根据ID获取实体
Entity Info = new Entity();
if (info== null)
{
return null;
}
fileName = "xxxxx(" +info.xxxx + ")的内容";
dic.Add("属性1", info.属性);
......
return dic;
}
#endregion
标签替换
#region 替换标签
/// <summary>
/// 替换内容
/// </summary>
/// <param name="sourceContent"></param>
/// <param name="dic"></param>
/// <returns></returns>
public static string ReplaceContent(string source, IDictionary<string, string> dic)
{
while (source.IndexOf("{#") >= 0 && source.IndexOf("#}") > source.IndexOf("{#"))
{
string key = source.Substring(source.IndexOf("{#") + 2, source.IndexOf("#}") - source.IndexOf("{#") - 2);
if (dic.ContainsKey(key))
{
source = source.Replace("{#" + key + "#}", dic[key]);
}
else
{
source = source.Replace("{#" + key + "#}", "");
}
}
return source;
}
#endregion