asp.Net Excelをインポートしてデータベースに記録する

4351 ワード

これはただの機能テストプログラムで、詳細は処理されていません.
前提条件:
ルートディレクトリの下にuploadfilesフォルダ(アップロードされたxlsファイルを保存するために使用)を作成します.
aspxセクション:
uploadfileとbuttonコントロールを追加すればいいです.
.csセクション:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace V3WEB
{
    public partial class UploadData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        #region   Excel    Excel        DataSet    
        /// <summary>
        ///   Excel    Excel        DataSet    
        /// </summary>
        /// <param name="filepath">Excel     </param>
        /// <param name="tableName">Excel   </param>
        /// <returns></returns>
        public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            OleDbConnection ExcelConn = new OleDbConnection(strCon);
            try
            {
                string strCom = string.Format("SELECT * FROM [Sheet1$]");
                ExcelConn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[" + tableName + "$]");
                ExcelConn.Close();
                return ds;
            }
            catch
            {
                ExcelConn.Close();
                return null;
            }
        }
        #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile == false)//HasFile    FileUpload       
            {
                Response.Write("<script>alert('    Excel  ')</script> ");
                return;//     ,  
            }
            string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension        
            if (IsXls != ".xls")
            {
                Response.Write("<script>alert('     Excel  ')</script>");
                return;//      Excel   ,  
            }
            string filename = FileUpload1.FileName;              //  Execle     DateTime    
            string savePath = Server.MapPath(("uploadfiles\\") + filename);//Server.MapPath            
            FileUpload1.SaveAs(savePath);                        //SaveAs                
            DataSet ds = ExcelSqlConnection(savePath, filename);           //       
            DataRow[] dr = ds.Tables[0].Select();            //    DataRow  
            int rowsnum = ds.Tables[0].Rows.Count;
            if (rowsnum == 0)
            {
                Response.Write("<script>alert('Excel    ,   !')</script>");   // Excel    ,       
            }
            else
            {
                string _Result = "";
                for (int i = 0; i < dr.Length; i++)
                {
                    //            “upfiles”     ,        ,             Excel  ,                     
                    string title = dr[i]["  "].ToString();
                    string linkurl = dr[i]["    "].ToString();
                    string categoryname = dr[i]["  "].ToString();
                    string customername = dr[i]["   "].ToString();
                    try
                    {
                        BLL.Erp.Stock.Factory.getST_CKNOBLL().ZZ_Upload_add(title, linkurl, categoryname, customername);
                    }
                    catch (Exception ex)
                    {
                        _Result = _Result + ex.Message + "\
\\r"; } } Response.Write("<script>alert(' :" + _Result + "')</script>"); Response.Write("<script>alert('Excle !');</script>"); } } } }

xlsファイルスタイル: