Asp.net的對Excel文檔的匯入匯出操作

來源:互聯網
上載者:User

標籤:

剛剛初入職場,在休閑的時間寫下了項目中用到的對Excel文檔操作的方法以及總結,多的不說,直接上代碼

public static void CreateExcel(DataSet ds, string FileName)

        {

            //resp = Page.Response;

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.Charset = "UTF-8";

 

            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");

            HttpContext.Current.Response.ContentType = "application/ms-excel";

            string colHeaders = "", ls_item = "";

            int i = 0;

 

            //定¨義?表括?對?象ó與?行D對?像?,?同?時骸?用?DataSet對?其?值μ進?行D初?始?化ˉ

            System.Data.DataTable dt = ds.Tables[0];

            DataRow[] myRow = dt.Select("");

            //取?得?數簓據Y表括?各÷列標括?題琣,?各÷標括?題琣之?間?以?\t分?割?,?最?後ó一?個?列標括?題琣後ó加ó回?車μ符?

            for (i = 0; i < dt.Columns.Count - 1; i++)

                colHeaders += dt.Columns[i].Caption.ToString() + "\t";

            colHeaders += dt.Columns[i].Caption.ToString() + "\n";

            //向òHTTP輸?出?流ⅰ?中D寫′入?取?得?的?數簓據Y信?息¢

            HttpContext.Current.Response.Write(colHeaders);

            //逐e行D處鋦理え?數簓據Y  

            foreach (DataRow row in myRow)

            {

                //在ú當獺?前°行D中D,?逐e列獲?得?數簓據Y,?數簓據Y之?間?以?\t分?割?,?結á束?時骸?加ó回?車μ符?\n

                for (i = 0; i < dt.Columns.Count - 1; i++)

                    ls_item += row[i].ToString() + "\t";

                ls_item += row[i].ToString() + "\n";

                //當獺?前行D數簓據Y寫′入?HTTP輸?出?流ⅰ?,?並¢且ò置?空?ls_item以?便?下?行D數簓據Y    

                HttpContext.Current.Response.Write(ls_item);

                ls_item = "";

            }

            //寫′緩o沖?區?中D的?數簓據Y到?HTTP頭?文?件t中D

            HttpContext.Current.Response.End();

        }

方法2:NPIO匯出Excel資料。這種方式方便快捷,要引入第三方的NPIO.dll的檔案,http://npoi.codeplex.com/releases/view/38113   

  protected void getExcel(DataTable dt, string FileName)

        {

            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();

            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");

            NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);

            for (int i = 0; i < dt.Columns.Count; i++)

            {

                headerrow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);

            }

 

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);

                for (int j = 0; j < dt.Columns.Count; j++)

                    row2.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());

            }

 

 

            //寫′入到用戶端

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            book.Write(ms);

            Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"));

            Response.BinaryWrite(ms.ToArray());

            book = null;

            ms.Close();

            ms.Dispose();

 

        }

直接在點擊事件調用即可

二,匯入Excel資料

匯入Excel需要引用微軟官方的OleDb驅動

protected void btnUpload_Click(object sender, EventArgs e)

        {

            if (txtFilePath.HasFile)

            {

                OleDbConnection conn = new OleDbConnection();

                OleDbCommand cmd = new OleDbCommand();

                OleDbDataAdapter da = new OleDbDataAdapter();

                DataSet ds = new DataSet();

                string query = null;

                string connString = "";

                //string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");

                string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();

                if (strFileType == ".xls" || strFileType == ".xlsx")

                {

                    txtFilePath.SaveAs(Server.MapPath("~/upload/" + strFileType));

                }

                string strNewPath = Server.MapPath("~/upload/" + strFileType);

 

                if (strFileType.Trim() == ".xls")

                {

                    connString = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + strNewPath + ";Extended Properties=‘Excel 12.0; HDR=Yes; IMEX=1‘";

                }

                else if (strFileType.Trim() == ".xlsx")

                {

                    connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";

                }

                query = "SELECT * FROM [Sheet1$]";

                conn = new OleDbConnection(connString);

 

                if (conn.State == ConnectionState.Closed) conn.Open();

 

                cmd = new OleDbCommand(query, conn);

                da = new OleDbDataAdapter(cmd);

                ds = new DataSet();

                da.Fill(ds);

          da.Dispose();

                conn.Close();

                conn.Dispose();

注意:如果使用上述的第一種方式先匯出Excel,然後在匯入Excel,會報錯,因為第一種方式匯出的不是標準的Excel,是html的方式匯出的,第二種NPIO匯出,這個是標準的Excel資料。

Asp.net的對Excel文檔的匯入匯出操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.