asp.net(C#)excel导入导出类
2012-06-19 14:23
423 查看
public class HExcel { #region 导入表格 /// <summary> /// 读取Excel文件,内容存储在DataSet中 /// </summary> /// <param name="fileName">文件路径</param> /// <param name="sSelect">选择语句{"A:F"表示选择A到F列,包含A,F列, "A1:B2"表示选择A1到B2范围,包括A1,B2}</param> /// <param name="bTitle">是否将第一行作为标题行,如果是则可以采用 dr["天津"] 的形式读取数据,否则采取dr[0]的形式</param> /// <returns></returns> public static DataTable ToDataSet(string fileName, string sSelect, bool bTitle) { //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES //IMEX有3个值:当IMEX=2 时,EXCEL文档中同时含有字符型和数字型时,比如第C列有3个值,2个为数值型 123,1个为字符型 ABC,当导入时, //页面不报错了,但库里只显示数值型的123,而字符型的ABC则呈现为空值。当IMEX=1时,无上述情况发生,库里可正确呈现 123 和 ABC. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=" + (bTitle ? "YES" : "NO") + ";IMEX=1\""; var conn = new OleDbConnection(strConn); string strExcel = string.Format(@"select * from [sheet1${0}]", sSelect); var ds = new DataSet(); try { conn.Open(); var xlsCommand = new OleDbDataAdapter(strExcel, strConn); xlsCommand.Fill(ds, "sheet1$"); } catch (Exception) { return null; } finally { conn.Close(); conn.Dispose(); } if (ds.Tables.Count > 0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0) return ds.Tables[0]; return null; } #endregion #region ExportToExcel:导出excel /// <summary> /// 将DataTable转成Excel