1 给出 demo源码: http://pan.baidu.com/s/1hqGMudY
提取码:pw4n
首先要引用 NPOI.dll (可在网上下载!)
2 //导入 3 public void OnSubmit() 4 { 5 string path = Server.MapPath("/upload/201410/27/201410271103461051.xls"); 6 FileStream fs = File.Open(path, FileMode.Open); 7 System.Data.DataTable dt = ConvertToDataTable(fs); 8 9 foreach (DataRow row in dt.Rows) 10 { 11 if (row["Mobile1"] != null) 12 { 13 Response.Write(row["Mobile1"].ToString() + " " + row["Mobile2"].ToString() + " 14 "); 15 } 16 } 17 Response.End(); 18 } 19 20 21 //excel转DataTable 22 public static DataTable ConvertToDataTable(System.IO.Stream excelFileStream) 23 { 24 HSSFWorkbook HSSFWorkbook = new HSSFWorkbook(excelFileStream); 25 DataTable dt = new DataTable(); 26 HSSFSheet sheet = (HSSFSheet)HSSFWorkbook.GetSheetAt(0); 27 System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); 28 int n = 0; 29 while (rows.MoveNext()) 30 { 31 HSSFRow row = (HSSFRow)rows.Current; 32 if (n == 0) 33 { 34 for (int i = 0; i < row.LastCellNum; i++) 35 { 36 HSSFCell cell = (HSSFCell)row.GetCell(i); 37 if (cell == null) 38 continue; 39 DataColumn column = new DataColumn(cell.StringCellValue); 40 41 dt.Columns.Add(column); 42 } 43 } 44 else 45 { 46 DataRow dtRow = dt.NewRow(); 47 string rValue = ""; 48 for (int i = 0, j = 0; i < row.LastCellNum; i++) 49 { 50 HSSFCell cell = (HSSFCell)row.GetCell(i); 51 if (cell == null) 52 { 53 dtRow[i] = ""; 54 } 55 else 56 { 57 dtRow[j] = cell.ToString(); 58 rValue = cell.ToString(); 59 j++; 60 } 61 } 62 if (string.IsNullOrEmpty(rValue.Trim())) 63 break; 64 dt.Rows.Add(dtRow); 65 } 66 n++; 67 } 68 return dt; 69 70 } 71 72
/// <summary>
/// Excel导出数据
/// </summary>
/// <param name="sbHtml">html标签</param>
/// <param name="fileName">文件名</param>
public static void ExportExcel(StringBuilder sbHtml, string fileName)
{
try
{
if (sbHtml.Length > 0)
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Charset = "Utf-8";
//HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls" );
HttpContext.Current.Response.Write(sbHtml.ToString());
HttpContext.Current.Response.End();
}
}
catch (Exception ex)
{
Logger.WriteLog("-----------Excel导出数据异常-----------
" + ex.ToString() + "
");
}
}