导入Excel和CSV文件
生活随笔
收集整理的這篇文章主要介紹了
导入Excel和CSV文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
讀取excel或csv文件中的數據暫時保存在DataTable中, 代碼如下:
public static DataTable ReadDataFromFile(string file, string sheet){string strConn = "";string extension = Path.GetExtension(file);string sqlStr = string.Empty;if (extension == ".csv"){strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='text;HDR=Yes;FMT=Delimited';Data Source={0}", Path.GetDirectoryName(file));sqlStr = string.Format("select * from {0}", Path.GetFileName(file));}else if (extension == ".xls"){strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'", file);sqlStr = string.Format("SELECT * FROM [{0}$]", sheet);}else if (extension == ".xlsx"){strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", file);sqlStr = string.Format("SELECT * FROM [{0}$]", sheet);}else{throw new Exception(string.Format("不支持的導入擴展名為{0}的文件!", extension));}OleDbConnection conn = new OleDbConnection(strConn);OleDbDataAdapter myCommand = new OleDbDataAdapter(sqlStr, strConn);DataTable dt = new DataTable();try{myCommand.Fill(dt);}catch (Exception ex){throw ex;}finally{conn.Close();}return dt;}
轉載于:https://www.cnblogs.com/Peter-Zhang/archive/2011/09/12/2172408.html
總結
以上是生活随笔為你收集整理的导入Excel和CSV文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基本数据类型与表达式5 - 零基础入门学
- 下一篇: 内嵌在客户端的网页出现刷新问题