【转】 (C#)利用Aspose.Cells组件导入导出excel文件

时间:2022-01-24 20:38:45

Aspose.Cells组件可以不依赖excel来导入导出excel文件:

导入:

public static System.Data.DataTable ReadExcel(String strFileName)
{
Workbook book = new Workbook();
book.Open(strFileName);
Worksheet sheet = book.Worksheets[];
Cells cells = sheet.Cells; return cells.ExportDataTableAsString(, , cells.MaxDataRow + , cells.MaxDataColumn + , true);
}

导出:

private static void Export<T>(IEnumerable<T> data, HttpResponse response)
{
Workbook workbook = new Workbook();
Worksheet sheet = (Worksheet)workbook.Worksheets[]; PropertyInfo[] ps = typeof(T).GetProperties();
var colIndex = "A"; foreach (var p in ps)
{ sheet.Cells[colIndex + ].PutValue(p.Name);
int i = ;
foreach (var d in data)
{
sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null));
i++;
} colIndex = ((char)(colIndex[] + )).ToString();
} response.Clear();
response.Buffer = true;
response.Charset = "utf-8";
response.AppendHeader("Content-Disposition", "attachment;filename=xxx.xls");
response.ContentEncoding = System.Text.Encoding.UTF8;
response.ContentType = "application/ms-excel";
response.BinaryWrite(workbook.SaveToStream().ToArray());
response.End();
}

转自:http://blog.csdn.net/weiky626/article/details/7514637