前台调用导出代码
function BM1DataCheck() {
loading = layer.confirm('确定导出?', function (index) {
var url = "xxxx" + new Date().getTime();
layer.close(loading);
loading = layer.load(0, {
shade: [0.1, '#fff']
});
$.get(url, function (data) {
layer.close(loading);
if (data.result == true) {
window.open(data.data);
layer.alert(data.msg + ",若浏览器未弹出下载框,<a style='color:blue' href='" + data.data + "' target='_blank'>可点此处重新下载</a>", { icon: 1 });
}
else {
layer.alert(data.msg, { icon: 0 });
}
});
});
}
常规导出
public JsonResult DownMissContract(int year, int month)
{
try
{
//保存的位置
string savePath = "/Areas/BM1/Content/POFile";
string fileName = "";
#region 获取数据
var dsfCalculation = new DSFCalculation_Impl();
//计算结果
var dt = dsfCalculation.MissContract(year, month);
#endregion
#region 下载合同服务费数据
{
//声明工作表
HSSFWorkbook wk = new HSSFWorkbook();
#region 导出Contract数据
ISheet sheet = wk.CreateSheet("Contract");
//设置表头
IRow cells = sheet.CreateRow(0);
#region 列名
cells.CreateCell(0).SetCellValue("ContractNo");
cells.CreateCell(1).SetCellValue("DealerCode");
#endregion
int i = 0;
foreach (DataRow dr in dt.Rows)
{
#region 数据
i++;
IRow rowtemp = sheet.CreateRow(i); //循环行
rowtemp.CreateCell(0).SetCellValue(dr[0].ToString());
rowtemp.CreateCell(1).SetCellValue(dr[1].ToString());
#endregion
}
#endregion
string dir = Server.MapPath("~" + savePath);
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
fileName = "ContractInfo" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
string filePath = dir + "\\" + fileName;
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
wk.Write(fs);
fs.Dispose();
}
#endregion
return Json(new { msg = "导出成功,差异数据已导出", result = true, data = WebCommon.WebPrefix + savePath + "/" + fileName }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { msg = "导出失败:" + ex.Message, result = false, data = "" }, JsonRequestBehavior.AllowGet);
}
}
分页导出、打包导出
public JsonResult ImportResult(bool cacheData, string calculationType, int year, int month, string brand, string usedType, string key, string rule, string sidx, string sord)
{
try
{
DBFactory.RemoveCache();
//PO压缩包的位置
string poPath = "/Areas/BM1/Content/POFile";
//PO excel存的位置
string savePath = poPath + "/" + year + "" + month.ToString().PadLeft(2, '0');
#region 获取数据
key = Server.UrlDecode(key);
rule = Server.UrlDecode(rule);
R_ContractInfo_Impl impl = new R_ContractInfo_Impl();
int totalCount = 0;
int totalPage = 0;
List<V_BIDealerContract> list = impl.GetPageList(calculationType, year, month, brand, usedType, key, sidx, sord, 1, int.MaxValue, "", out totalCount, out totalPage, "", cacheData);
DataTable dt = new DataTable();
//计算结果
var ruleList = DBFactory.ExecuteServiceFee(cacheData, rule, year, month, list);
#endregion
#region 经销商数据计算
List<string> DealerCode = ruleList.Select(x => x.DealerInfo.DealerInfoForDB.DealerCode).Distinct().ToList();
List<R_Dealer> dealers = new List<R_Dealer>();
foreach (var item in DealerCode)
{
var contractList = ruleList.Where(x => x.DealerInfo.DealerInfoForDB.DealerCode == item).ToList();
R_Dealer entity = new R_Dealer();
entity.DealerCode = item;
dealers.Add(entity);
}
#endregion
#region 下载经销商服务费数据
{
//声明工作表
HSSFWorkbook wk = new HSSFWorkbook();
#region 导出Dealer数据
{
ISheet sheet = wk.CreateSheet("ServiceFeeByDealer");
//设置表头
IRow cells = sheet.CreateRow(0);
#region 列名
cells.CreateCell(0).SetCellValue("DealerCode");
cells.CreateCell(1).SetCellValue("DealerName");
#endregion
int i = 0;
foreach (var item in dealers)
{
i++;
IRow rowtemp = sheet.CreateRow(i); //循环行
}
}
#endregion
string dir = Server.MapPath("~" + savePath);
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
string fileName = year + "" + month.ToString().PadLeft(2, '0') + "_ServiceFeeByDealer.xls";
string filePath = dir + "\\" + fileName;
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
wk.Write(fs);
fs.Dispose();
}
#endregion
#region 下载合同服务费数据
{
//声明工作表
HSSFWorkbook wk = new HSSFWorkbook();
#region 导出Contract数据
//处理65536问题
int rowSize = 65000;//页大小
//总页数
int pageSize = (int)Math.Ceiling((ruleList.Count * 0.1) / (rowSize * 0.1));
for (int currentPage = 1; currentPage <= pageSize; currentPage++)
{
var dbList = ruleList.Skip((currentPage - 1) * rowSize).Take(rowSize).ToList();
ISheet sheet = wk.CreateSheet("ServiceFeeByContract_" + currentPage.ToString().PadLeft(2, '0'));
//设置表头
IRow cells = sheet.CreateRow(0);
#region 列名
cells.CreateCell(0).SetCellValue("PONumber");
#endregion
int i = 0;
foreach (var entity in dbList)
{
#region 数据
i++;
IRow rowtemp = sheet.CreateRow(i); //循环行
rowtemp.CreateCell(0).SetCellValue(entity.DealerInfo.DealerInfoForDB.PONumber);
#endregion
}
}
#endregion
string dir = Server.MapPath("~" + savePath);
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
string fileName = year + "" + month.ToString().PadLeft(2, '0') + "_ServiceFeeByContract.xls";
string filePath = dir + "\\" + fileName;
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
wk.Write(fs);
fs.Dispose();
}
#endregion
string poDir = Server.MapPath("~" + savePath);
string poZip = Server.MapPath("~" + poPath);
string file = year + "" + month.ToString().PadLeft(2, '0') + ".zip";
if (System.IO.File.Exists(poZip + "\\" + file))
{
System.IO.File.Delete(poZip + "\\" + file);
}
//压缩打包
ZipClass.CreatZipFileFromDirectory(poDir, poZip + "\\" + file, System.IO.Compression.CompressionLevel.Fastest);
return Json(new { msg = "导出成功,详情数据已导出", result = true, data = WebCommon.WebPrefix + poPath + "/" + file }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { msg = "导出失败:" + ex.Message, result = false, data = "" }, JsonRequestBehavior.AllowGet);
}
}
打包帮助类
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aZaaS.Business.DAL.Util
{
/// <summary>
/// 压缩和解压文件
/// </summary>
public class ZipClass
{
#region Methods
/// <summary>
/// 创建 zip 存档,该存档包含指定目录的文件和目录。
/// </summary>
/// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="compressionLevel"></param>
/// <param name="includeBaseDirectory">压缩包中是否包含父目录</param>
public static bool CreatZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName,
CompressionLevel compressionLevel = CompressionLevel.NoCompression,
bool includeBaseDirectory = true)
{
if (Directory.Exists(sourceDirectoryName)) //目录
if (!File.Exists(destinationArchiveFileName))
{
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
compressionLevel, includeBaseDirectory);
}
else
{
var toZipFileDictionaryList = GetAllDirList(sourceDirectoryName, includeBaseDirectory);
using (
var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
)
{
foreach (var toZipFileKey in toZipFileDictionaryList.Keys)
if (toZipFileKey != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(toZipFileKey);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(toZipFileKey, toZipFileDictionaryList[toZipFileKey],
compressionLevel);
}
}
}
else if (File.Exists(sourceDirectoryName))
if (!File.Exists(destinationArchiveFileName))
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
compressionLevel, false);
else
using (
var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
)
{
if (sourceDirectoryName != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(sourceDirectoryName);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(sourceDirectoryName, toZipedFileName, compressionLevel);
}
}
else
return false;
return true;
}
/// <summary>
/// 创建 zip 存档,该存档包含指定目录的文件和目录。
/// </summary>
/// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="compressionLevel"></param>
public static bool CreatZipFileFromDictionary(Dictionary<string, string> sourceDirectoryName,
string destinationArchiveFileName,
CompressionLevel compressionLevel = CompressionLevel.NoCompression)
{
using (FileStream zipToOpen = new FileStream(destinationArchiveFileName, FileMode.OpenOrCreate))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
foreach (var toZipFileKey in sourceDirectoryName.Keys)
if (toZipFileKey != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(toZipFileKey);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(toZipFileKey, sourceDirectoryName[toZipFileKey],
compressionLevel);
}
}
}
return true;
}
/// <summary>
/// 递归删除文件夹目录及文件
/// </summary>
/// <param name="baseDirectory"></param>
/// <returns></returns>
public static bool DeleteFolder(string baseDirectory)
{
var successed = true;
if (Directory.Exists(baseDirectory)) //如果存在这个文件夹删除之
{
foreach (var directory in Directory.GetFileSystemEntries(baseDirectory))
if (File.Exists(directory))
File.Delete(directory); //直接删除其中的文件
else
successed = DeleteFolder(directory); //递归删除子文件夹
Directory.Delete(baseDirectory); //删除已空文件夹
}
return successed;
}
/// <summary>
/// 调用bat删除目录,以防止系统底层的异步删除机制
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
public static bool DeleteDirectoryWithCmd(string dirPath)
{
var process = new Process(); //string path = ...;//bat路径
var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C rd /S /Q \"" + dirPath + "\"")
{
UseShellExecute = false,
RedirectStandardOutput = true
}; //第二个参数为传入的参数,string类型以空格分隔各个参数
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
if (string.IsNullOrWhiteSpace(output))
return true;
return false;
}
/// <summary>
/// 调用bat删除文件,以防止系统底层的异步删除机制
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool DelFileWithCmd(string filePath)
{
var process = new Process(); //string path = ...;//bat路径
var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C del /F /S /Q \"" + filePath + "\"")
{
UseShellExecute = false,
RedirectStandardOutput = true
}; //第二个参数为传入的参数,string类型以空格分隔各个参数
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
if (output.Contains(filePath))
return true;
return false;
}
/// <summary>
/// 获取目录下所有[文件名,要压缩的相对文件名]字典
/// </summary>
/// <param name="strBaseDir"></param>
/// <param name="includeBaseDirectory"></param>
/// <param name="namePrefix"></param>
/// <returns></returns>
public static Dictionary<string, string> GetAllDirList(string strBaseDir,
bool includeBaseDirectory = false, string namePrefix = "")
{
var resultDictionary = new Dictionary<string, string>();
var directoryInfo = new DirectoryInfo(strBaseDir);
var directories = directoryInfo.GetDirectories();
var fileInfos = directoryInfo.GetFiles();
if (includeBaseDirectory)
namePrefix += directoryInfo.Name + "\\";
foreach (var directory in directories)
resultDictionary =
resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix))
.ToDictionary(k => k.Key, k => k.Value); //.FullName是某个子目录的绝对地址,
foreach (var fileInfo in fileInfos)
if (!resultDictionary.ContainsKey(fileInfo.FullName))
resultDictionary.Add(fileInfo.FullName, namePrefix + fileInfo.Name);
return resultDictionary;
}
/// <summary>
/// Zip解压并更新目标文件
/// </summary>
/// <param name="zipFilePath">Zip压缩包路径</param>
/// <param name="unZipDir">解压目标路径</param>
/// <returns></returns>
public static bool UnZip(string zipFilePath, string unZipDir)
{
bool resualt;
unZipDir = unZipDir.EndsWith(@"\") ? unZipDir : unZipDir + @"\";
var directoryInfo = new DirectoryInfo(unZipDir);
if (!directoryInfo.Exists)
directoryInfo.Create();
var fileInfo = new FileInfo(zipFilePath);
if (!fileInfo.Exists)
return false;
using (
var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite,
FileShare.Read))
{
using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
foreach (var zipArchiveEntry in archive.Entries)
if (!zipArchiveEntry.FullName.EndsWith("/"))
{
var entryFilePath = Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"),
@"^\\*", "");
var filePath = directoryInfo + entryFilePath; //设置解压路径
var content = new byte[zipArchiveEntry.Length];
zipArchiveEntry.Open().Read(content, 0, content.Length);
if (File.Exists(filePath) && content.Length == new FileInfo(filePath).Length)
continue; //跳过相同的文件,否则覆盖更新
var sameDirectoryNameFilePath = new DirectoryInfo(filePath);
if (sameDirectoryNameFilePath.Exists)
{
sameDirectoryNameFilePath.Delete(true);
DeleteDirectoryWithCmd(filePath);
/*if (!DeleteDirectoryWithCmd(filePath))
{
Console.WriteLine(filePath + "删除失败");
resualt = false;
break;
}*/
}
var sameFileNameFilePath = new FileInfo(filePath);
if (sameFileNameFilePath.Exists)
{
sameFileNameFilePath.Delete();
DelFileWithCmd(filePath);
/*if (!DelFileWithCmd(filePath))
{
Console.WriteLine(filePath + "删除失败");
resualt = false;
break;
}*/
}
var greatFolder = Directory.GetParent(filePath);
if (!greatFolder.Exists) greatFolder.Create();
File.WriteAllBytes(filePath, content);
}
}
}
resualt = true;
return resualt;
}
#endregion
}
}