using Aspose.Cells;
using System;
using System.Data;
using System.IO;
using System.Text;
namespace Core.Util
{
public class AsposeOfficeHelper
{
static AsposeOfficeHelper()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
public static byte[] DataTableToExcelBytes(DataTable dt)
{
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
Cells cells = sheet.Cells;
int Colnum = dt.Columns.Count;
int Rownum = dt.Rows.Count;
for (int i = 0; i < Colnum; i++)
{
cells[0, i].PutValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < Rownum; i++)
{
for (int k = 0; k < Colnum; k++)
{
cells[1 + i, k].PutValue(dt.Rows[i][k].ToString());
}
}
sheet.AutoFitColumns();
sheet.AutoFitRows();
var ms = new MemoryStream();
book.Save(ms, SaveFormat.Excel97To2003);
return ms.ToArray();
}
public static byte[] ExportExcelByTemplate(string templateFile, params (string SourceName, object Data)[] dataSource)
{
if (templateFile.IsNullOrEmpty())
throw new Exception("模板不能为空");
if (dataSource.Length == 0)
throw new Exception("数据源不能为空");
WorkbookDesigner designer = new WorkbookDesigner
{
Workbook = new Workbook(templateFile)
};
var workBook = designer.Workbook;
dataSource.ForEach(aDataSource =>
{
designer.SetDataSource(aDataSource.SourceName, aDataSource.Data);
});
designer.Process();
using (MemoryStream stream = new MemoryStream())
{
workBook.Save(stream, SaveFormat.Excel97To2003);
var fileBytes = stream.ToArray();
return fileBytes;
}
}
public static DataTable ReadExcel(string fileNmae)
{
Workbook book = new Workbook(fileNmae);
Worksheet sheet = book.Worksheets[0];
Cells cells = sheet.Cells;
return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
}
public static DataTable ReadExcel(string fileNmae,bool exportColumnName)
{
Workbook book = new Workbook(fileNmae);
Worksheet sheet = book.Worksheets[0];
Cells cells = sheet.Cells;
return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, exportColumnName);
}
public static DataTable ReadExcel(byte[] fileBytes)
{
return ReadExcel(fileBytes, true);
}
public static DataTable ReadExcel(byte[] fileBytes,bool exportColumnName)
{
using (MemoryStream ms = new MemoryStream(fileBytes))
{
Workbook book = new Workbook(ms);
Worksheet sheet = book.Worksheets[0];
Cells cells = sheet.Cells;
return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, exportColumnName);
}
}
}
}