Aspose.Cells组件可以不依赖excel来导入导出excel文件:
导入:
[csharp] view plain copy
print?
- public static System.Data.DataTable ReadExcel(String strFileName)
- {
- Workbook book = new Workbook();
- book.Open(strFileName);
- Worksheet sheet = book.Worksheets[0];
- Cells cells = sheet.Cells;
- return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
- }
public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true); }
导出:
[csharp] view plain copy
print?
- private static void Export<T>(IEnumerable<T> data, HttpResponse response)
- {
- Workbook workbook = new Workbook();
- Worksheet sheet = (Worksheet)workbook.Worksheets[0];
- PropertyInfo[] ps = typeof(T).GetProperties();
- var colIndex = "A";
- foreach (var p in ps)
- {
- sheet.Cells[colIndex + 1].PutValue(p.Name);
- int i = 2;
- foreach (var d in data)
- {
- sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null));
- i++;
- }
- colIndex = ((char)(colIndex[0] + 1)).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();
- }
private static void Export<T>(IEnumerable<T> data, HttpResponse response) { Workbook workbook = new Workbook(); Worksheet sheet = (Worksheet)workbook.Worksheets[0]; PropertyInfo[] ps = typeof(T).GetProperties(); var colIndex = "A"; foreach (var p in ps) { sheet.Cells[colIndex + 1].PutValue(p.Name); int i = 2; foreach (var d in data) { sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null)); i++; } colIndex = ((char)(colIndex[0] + 1)).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
时间: 2024-10-19 17:52:29