ASP.NET读取Excel中的数据转存到数据库(一)

来源:互联网 发布:js文字切换效果代码 编辑:程序博客网 时间:2024/05/16 02:12

【问题描述】

近日需要做一些数据仓库的内容,发现数据库搭好了以后,所有的数据文件都是Excel存储的。然而数据又是及其繁杂,所以在创建好了事实表和维度表以后,准备自己写一个代码将Excel中多维的数据导入到数据库中。Excel表的部分数据如下图所示


所以需要对数据进行处理,处理之后添加到数据库中。

【准备工作】

首先需要找到从Excel读取数据的代码。参考网址:http://www.jb51.net/article/34096.htm。代码如下:

(1)页面上的代码

<div>       <%-- 文件上传控件  用于将要读取的文件上传 并通过此控件获取文件的信息--%>      <asp:FileUpload ID="fileSelect" runat="server" />          <%-- 点击此按钮执行读取方法--%>       <asp:Button ID="btnRead" runat="server" Text="ReadStart" /></div>  

(2)后台处理代码

 //声明变量(属性) string currFilePath = string.Empty; //待读取文件的全路径  string currFileExtension = string.Empty;  //文件的扩展名  //Page_Load事件 注册按钮单击事件  protected void Page_Load(object sender,EventArgs e)  {       }  //按钮单击事件   //里面的3个方法将在下面给出 protected void btnRead_Click(object sender,EventArgs e) {     Upload();  //上传文件方法     if(this.currFileExtension ==".xlsx" || this.currFileExtension ==".xls")       {            DataTable dt = ReadExcelToTable(currFilePath);  //读取Excel文件(.xls和.xlsx格式)       }       else if(this.currFileExtension == ".csv")         {               DataTable dt = ReadExcelWidthStream(currFilePath);  //读取.csv格式文件         } }///<summary>///上传文件到临时目录中 ///</ummary>private void Upload(){HttpPostedFile file = this.fileSelect.PostedFile;string fileName = file.FileName;string tempPath = System.IO.Path.GetTempPath(); //获取系统临时文件路径fileName = System.IO.Path.GetFileName(fileName); //获取文件名(不带路径)this.currFileExtension = System.IO.Path.GetExtension(fileName); //获取文件的扩展名this.currFilePath = tempPath + fileName; //获取上传后的文件路径 记录到前面声明的全局变量file.SaveAs(this.currFilePath); //上传}///<summary>///读取xls\xlsx格式的Excel文件的方法 ///</ummary>///<param name="path">待读取Excel的全路径</param>///<returns></returns>private DataTable ReadExcelToTable(string path){//连接字符串string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出现多余的空格 而且分号注意//string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 07以下版本 因为本人用Office2010 所以没有用到这个连接字符串 可根据自己的情况选择 或者程序判断要用哪一个连接字符串using(OleDbConnection conn = new OleDbConnection(connstring)){conn.Open();DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"}); //得到所有sheet的名字string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一个sheet的名字string sql = string.Format("SELECT * FROM [{0}],firstSheetName); //查询字符串OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);DataSet set = new DataSet();ada.Fill(set);return set.Tables[0];}}///<summary>///读取csv格式的Excel文件的方法 ///</ummary>///<param name="path">待读取Excel的全路径</param>///<returns></returns>private DataTable ReadExcelWithStream(string path){DataTable dt = new DataTable();bool isDtHasColumn = false; //标记DataTable 是否已经生成了列StreamReader reader = new StreamReader(path,System.Text.Encoding.Default); //数据流while(!reader.EndOfStream){string meaage = reader.ReadLine();string[] splitResult = message.Split(new char[]{','},StringSplitOption.None); //读取一行 以逗号分隔 存入数组DataRow row = dt.NewRow();for(int i = 0;i<splitResult.Length;i++){if(!isDtHasColumn) //如果还没有生成列{dt.Columns.Add("column" + i,typeof(string));}row[i] = splitResult[i];}dt.Rows.Add(row); //添加行isDtHasColumn = true; //读取第一行后 就标记已经存在列 再读取以后的行时,就不再生成列}return dt;}

【后续工作】

将Excel表存入到DataTable对象中,可以将读取到的表格数据转存到数据库的事实表中。将所需要的时间、地域以及品种的ID值读取以后,开始与Excel表中的数据一起存放到数据库中。部分代码如下所示

int i, j;            int region = 0;            //获取作物ID值            cropnumber = int.Parse(CropID.Text.ToString());            //获得更新数据库类型            if (mianji.Checked == true)  //遇到播种面积时新增数据库条目            {                for(i=2;i<40;i++)   //省份                {                    if (i == 3 || i == 9 || i == 13 || i == 21 || i == 28 || i == 34)  //跳过空白区域                        continue;                    //读取地域ID值                    string proname = exceldt.Rows[i][0].ToString().Replace(" ", "");                    string sqlstr = "select Region_ID from [DimRegion] where Province_Name='" + proname + "'";                    DataTable dt = new DataTable();                    dt = BaseClass1.ReadTable(sqlstr);                    region = int.Parse(dt.Rows[0][0].ToString());                    for(j=1;j<60;j++)  //时间                    {                        float area = float.Parse(exceldt.Rows[i][j].ToString());                        string str = "insert into[FactCropProducts](Time_ID,Region_ID,Croptype_ID,Area) values(" + j + "," + region + "," + cropnumber + "," + area + ")";                        BaseClass1.execsql(str);                    }                }            }

【后记】

这样写一个程序读取Excel中的数据,大大节省了时间。但是还有几个未解决的问题:

(1)如果Excel表第一个sheet的名字为中文名,第二个sheet为Sheet1。则使用上面的代码虽然是读取第一个sheet的名称,但是实际却读到的是Sheet1的内容。

(2)如果数据量巨大,需要的品种又多,这个代码就会有很大缺陷。就要一个一个输入品种ID,然后一个一个Excel表进行导入。浪费了人力也浪费了时间,所以这个代码的改进点还是不少的。

0 0
原创粉丝点击