依赖包
导出zip不需要依赖包,导出excel需要依赖包NPOI
zip导出模板实体
/// <summary>
/// 单文件导出入口
/// </summary>
public class SingleFileExportEntry
{
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileExportEntry"/> class.
/// </summary>
/// <param name="entryName">压缩包内单文件的文件名</param>
/// <param name="bytes">文件字节流</param>
public SingleFileExportEntry(string entryName, byte[] bytes)
{
if (string.IsNullOrEmpty(entryName))
{
throw new ArgumentNullException(nameof(entryName));
}
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
this.Bytes = bytes;
this.EntryName = entryName;
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileExportEntry"/> class.
/// </summary>
/// <param name="entryName">压缩包内单文件的文件名</param>
/// <param name="text">单个文本文件的内容</param>
public SingleFileExportEntry(string entryName, string text)
: this(entryName, text, Encoding.UTF8)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileExportEntry"/> class.
/// </summary>
/// <param name="entryName">压缩包内单文件的文件名</param>
/// <param name="text">单个文本文件的内容</param>
/// <param name="encoding">编码</param>
public SingleFileExportEntry(string entryName, string text, Encoding encoding)
{
if (string.IsNullOrEmpty(entryName))
{
throw new ArgumentNullException(nameof(entryName));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
this.Bytes = encoding.GetBytes(text);
this.EntryName = entryName;
}
/// <summary>
/// 单文件字节流
/// </summary>
public byte[] Bytes { get; }
/// <summary>
/// 压缩包内的单文件名
/// </summary>
public string EntryName { get; }
导出zip为字节流
/// <summary>
/// 导出zip
/// </summary>
/// <param name="entries">压缩包单文件集合</param>
/// <returns>字节流</returns>
public static byte[] ExportZipFile(IEnumerable<SingleFileExportEntry> entries)
{
byte[] res = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var entryCount = entries.Count();
for (int i = 0; i < entryCount; i++)
{
SingleFileExportEntry entryEntity = entries.ElementAt(i); // 压缩文件模板实体
ZipArchiveEntry entry = zip.CreateEntry(entryEntity.EntryName); // 创建被压缩文件
using (Stream sw = entry.Open())
{
sw.Write(entryEntity.Bytes, 0, entryEntity.Bytes.Length); // 被压缩文件流写入stream
}
}
// 重新计算压缩文件大小
foreach (MethodInfo method in zip.GetType().GetRuntimeMethods())
{
if (method.Name == "WriteFile")
{
method.Invoke(zip, new object[0]);
}
}
res = new byte[ms.Length];
ms.Position = 0;
ms.Read(res, 0, res.Length);// 读取文件流到res
ms.Position = ms.Position; // 重置ms的流指针位置
}
}
}
catch (Exception e)
{
LogHelper.LogError(e.Message, e);
}
return res;
}
导出excel
/// <summary>
/// 导出list为excel
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="lists">列表</param>
/// <param name="name">名字</param>
/// <param name="cellHeader">导出列:对应字段为key,导出的中文字为value</param>
/// <param name="timeFormat">时间格式化</param>
/// <returns>buty[]</returns>
public static byte[] Export2Excel<T>(IEnumerable<T> lists, string name, Dictionary<string, string> cellHeader = null, string timeFormat = "yyyy-MM-dd HH:mm:ss")
{
MemoryStream ms = new MemoryStream();
try
{
HSSFWorkbook workBook = new HSSFWorkbook();
ISheet sheet = workBook.CreateSheet(name);
IRow header = sheet.CreateRow(0);
int cellHeaderIndex = 0;
if (cellHeader == null || cellHeader.Count == 0)
{
cellHeader = new Dictionary<string, string>();
var props = typeof(T).GetProperties();
foreach (var prop in props)
{
cellHeader.TryAdd(prop.Name, prop.Name);
}
}
if (cellHeader?.Count > 0)
{
foreach (var item in cellHeader)
{
header.CreateCell(cellHeaderIndex++).SetCellValue(item.Value);
}
}
int rowIndex = cellHeader?.Count > 0 ? 1 : 0;
Type sourceType = typeof(T);
foreach (T item in lists)
{
IRow tempRow = sheet.CreateRow(rowIndex); // 创建新的一行
var tempCellIndex = 0; // 当前所处的单元格索引
foreach (var cell in cellHeader)
{
PropertyInfo prop = sourceType.GetProperty(cell.Key); // 获取当前属性
if (prop != null && prop.CanRead == true)
{
object value = prop.GetValue(item);
Type cellType = prop.PropertyType;
if (value != null)
{
if (cellType == typeof(DateTime) || cellType == typeof(DateTime?))
{
DateTime time = Convert.ToDateTime(value);
string timeString = GlobalConstant.EmptyString;
if (time != new DateTime(1900, 1, 1))
{
timeString = string.IsNullOrEmpty(timeFormat) ? time.ToString("yyyy-MM-dd HH:mm:ss") : time.ToString(timeFormat);
}
tempRow.CreateCell(tempCellIndex++).SetCellValue(timeString);
}
else if (
cellType == typeof(double) ||
cellType == typeof(decimal) ||
cellType == typeof(int) ||
cellType == typeof(long) ||
cellType == typeof(double?) ||
cellType == typeof(decimal?) ||
cellType == typeof(int?) ||
cellType == typeof(long?))
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(Convert.ToDouble(value));
}
else if (cellType == typeof(bool) || cellType == typeof(bool?))
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(Convert.ToBoolean(value));
}
else
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(Convert.ToString(value));
}
}
else
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(GlobalConstant.EmptyString);
}
}
}
rowIndex++;
}
workBook.Write(ms);
byte[] data = ms.ToArray();
return data;
}
catch
{
throw;
}
finally
{
ms.Close();
ms.Dispose();
}
}
/// <summary>
/// 导出指定列的数据
/// </summary>
/// <param name="dataTable">dataTable</param>
/// <param name="name">name</param>
/// <param name="cellHeader">导出列:对应字段为key,导出的中文字为value</param>
/// <param name="timeFormat">格式化时间</param>
/// <returns>二进制数组</returns>
public static byte[] Export2Excel(DataTable dataTable, string name, Dictionary<string, string> cellHeader = null, string timeFormat = "yyyy-MM-dd HH:mm:ss")
{
if (dataTable == null || dataTable.Rows.Count <= 0)
{
return null;
}
MemoryStream ms = new MemoryStream();
HSSFWorkbook workBook = new HSSFWorkbook();
try
{
ISheet sheet = workBook.CreateSheet(name);
IRow header = sheet.CreateRow(0);
int cellHeaderIndex = 0;
if (cellHeader == null || cellHeader.Count == 0)
{
cellHeader = new Dictionary<string, string>();
foreach (DataColumn column in dataTable.Columns)
{
cellHeader.Add(column.ColumnName, column.ColumnName);
}
}
foreach (var item in cellHeader)
{
header.CreateCell(cellHeaderIndex++).SetCellValue(item.Value);
}
int rowIndex = 1;
foreach (DataRow row in dataTable.Rows)
{
IRow tempRow = sheet.CreateRow(rowIndex); // 创建新的一行
var tempCellIndex = 0; // 当前所处的单元格索引
foreach (var cell in cellHeader)
{
object value = row[cell.Value];
if (value == null || value == DBNull.Value)
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(GlobalConstant.EmptyString);
continue;
}
DataColumn column = dataTable.Columns[cell.Value];
if (
column.DataType == typeof(double) ||
column.DataType == typeof(decimal) ||
column.DataType == typeof(int) ||
column.DataType == typeof(long) ||
column.DataType == typeof(double?) ||
column.DataType == typeof(decimal?) ||
column.DataType == typeof(int?) ||
column.DataType == typeof(long?))
{
double currentData = Convert.ToDouble(value);
tempRow.CreateCell(tempCellIndex++).SetCellValue(currentData);
}
else if (column.DataType == typeof(DateTime) || column.DataType == typeof(DateTime?))
{
DateTime time = Convert.ToDateTime(value);
string timeString = string.IsNullOrEmpty(timeFormat) ? time.ToString("yyyy-MM-dd HH:mm:ss") : time.ToString(timeFormat);
if (time == new DateTime(1900, 1, 1))
{
timeString = GlobalConstant.EmptyString;
}
tempRow.CreateCell(tempCellIndex++).SetCellValue(timeString);
}
else if (column.DataType == typeof(bool) || column.DataType == typeof(bool?))
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(Convert.ToBoolean(value));
}
else
{
tempRow.CreateCell(tempCellIndex++).SetCellValue(Convert.ToString(value));
}
}
rowIndex++;
}
workBook.Write(ms);
byte[] data = ms.ToArray();
return data;
}
catch
{
throw;
}
finally
{
ms.Close();
ms.Dispose();
workBook.Close();
}
}
···