后端
- excel下载
IWorkbook workbook = new XSSFWorkbook();
using (var memoryStream = new MemoryStream())
{
workbook.Write(memoryStream);
var byteArray = memoryStream.ToArray();
return Convert.ToBase64String(byteArray);
}
- zip下载
IWorkbook workbook = new XSSFWorkbook();
Dictionary<string, string> dictFile = new Dictionary<string, string>();
string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "down_temp", "Zip");
if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
string filePath = Path.Combine(folderPath, $"{Guid.NewGuid().ToString("N")}.xlsx");
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
dictFile.Add("视图.xlsx", filePath);
public MemoryStream ExportMultipleExcelAndCompress(Dictionary<string, string> dictFile)
{
var compressedStream = new MemoryStream();
using (var zipArchive = new ZipArchive(compressedStream, ZipArchiveMode.Create, true))
{
foreach (var fileInfo in dictFile)
{
AddWorkbookToZip(fileInfo.Value, zipArchive, fileInfo.Key);
}
}
compressedStream.Seek(0, SeekOrigin.Begin);
return compressedStream;
}
private void AddWorkbookToZip(string filePath, ZipArchive zipArchive, string entryName)
{
var zipEntry = zipArchive.CreateEntry(entryName);
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var entryStream = zipEntry.Open())
{
fileStream.CopyTo(entryStream);
}
}
try
{
using (MemoryStream compressedStream = ExportMultipleExcelAndCompress(dictFile))
{
using (var memoryStream = new MemoryStream())
{
compressedStream.CopyTo(memoryStream);
result.File = Convert.ToBase64String(memoryStream.ToArray());
}
}
}
finally
{
foreach (var fileInfo in dictFile)
{
File.Delete(fileInfo.Value);
}
}
前端
let file = '';
let fileType = 0;
const byteCharacters = atob(file);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
let blob;
let fileName;
if (fileType === 0) {
blob = new Blob([byteArray], { type: 'application/zip' });
fileName = "下载.zip";
} else if (fileType === 1) {
blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
fileName = "下载.xlsx";
} else {
console.error('未知的文件类型');
return;
}
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.target = '_blank';
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);