excel导入 导出 兼容各个版本服务器不装EXCEL也可以

时间:2023-03-09 00:39:27
excel导入 导出 兼容各个版本服务器不装EXCEL也可以
 给出 demo源码: http://pan.baidu.com/s/1hqGMudY            提取码:pw4n
首先要引用 NPOI.dll (可在网上下载!)
//导入
public void OnSubmit()
{
string path = Server.MapPath("/upload/201410/27/201410271103461051.xls");
FileStream fs = File.Open(path, FileMode.Open);
System.Data.DataTable dt = ConvertToDataTable(fs); foreach (DataRow row in dt.Rows)
{
if (row["Mobile1"] != null)
{
Response.Write(row["Mobile1"].ToString() + " " + row["Mobile2"].ToString() + "
");
}
}
Response.End();
} //excel转DataTable
public static DataTable ConvertToDataTable(System.IO.Stream excelFileStream)
{
HSSFWorkbook HSSFWorkbook = new HSSFWorkbook(excelFileStream);
DataTable dt = new DataTable();
HSSFSheet sheet = (HSSFSheet)HSSFWorkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
int n = 0;
while (rows.MoveNext())
{
HSSFRow row = (HSSFRow)rows.Current;
if (n == 0)
{
for (int i = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = (HSSFCell)row.GetCell(i);
if (cell == null)
continue;
DataColumn column = new DataColumn(cell.StringCellValue); dt.Columns.Add(column);
}
}
else
{
DataRow dtRow = dt.NewRow();
string rValue = "";
for (int i = 0, j = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = (HSSFCell)row.GetCell(i);
if (cell == null)
{
dtRow[i] = "";
}
else
{
dtRow[j] = cell.ToString();
rValue = cell.ToString();
j++;
}
}
if (string.IsNullOrEmpty(rValue.Trim()))
break;
dt.Rows.Add(dtRow);
}
n++;
}
return dt; }

/// <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导出数据异常-----------\r\n" + ex.ToString() + "\r\n");
}
}