Excel文件上传及读取


            //上传文件
            string root = "~/Upload/Files/StorageOutFile/";
            string path = Server.MapPath(root);
            string datePath = string.Empty;
            datePath += DateTime.Now.Year.ToString() + "/";
            datePath += DateTime.Now.Month.ToString("D2") + "/";
            datePath += DateTime.Now.Day.ToString("D2") + "/";
            root += datePath;
            path += "/" + datePath;
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            string fileName = root + DateTime.Now.ToFileTime() + Path.GetExtension(Request.Files[0].FileName);
            string FileUrl = Server.MapPath(fileName);
            Request.Files[0].SaveAs(FileUrl);


            //读取EXCEL1
            DataSet ds = new DataSet();
            Workbook workbook = new Workbook(FileUrl);
            Worksheet sheet = workbook.Worksheets[0];
            Cells cells = sheet.Cells;
            DataTable tab = new DataTable();
            for (int i = 0; i <= cells.MaxColumn; i++)
            {
                tab.Columns.Add(cells[0, i].StringValue.Trim(), typeof(System.String));
            }
            DataRow dr;
            for (int i = 1; i <= cells.MaxDataRow; i++)
            {
                dr = tab.NewRow();
                for (int j = 0; j <= cells.MaxDataColumn; j++)
                {
                    string data = cells[i, j].StringValue.Trim();
                    dr[j] = data;
                }
                tab.Rows.Add(dr);
            }
            ds.Tables.Add(tab);


            //读取EXCEL2
            //DataSet ds;
            //string strCon;
            //if (Path.GetExtension(HttpContext.Request.Files[0].FileName) == ".xls")
            //    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FileUrl + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            //else
            //    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FileUrl + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

            //OleDbConnection myConn = new OleDbConnection(strCon);
            //myConn.Open();
            //DataTable table = myConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            //string tableName = table.Rows[0]["Table_Name"].ToString();

            //string strCom = string.Format(" SELECT * FROM [{0}]", tableName);
            //OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            //ds = new DataSet();
            //myCommand.Fill(ds);
            //myConn.Close();



            DataTable dt = ds.Tables[0];
            string str = dt.Rows[0][3].ToString();

posted @ 2016-04-29 13:43  罪後忆支湮  阅读(139)  评论(0)    收藏  举报