Asp.Net Excel导入

页面前段添加一个上传控件FileUpload,一个button

点击button,后台代码

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" && IsXls != ".xlsx")
            {
                Response.Write("<script>alert('只可以选择Excel文件')</script>");
                return;//当选择的不是Excel文件时,返回
            }


               string filename = FileUpload1.FileName;

               string savePath = FileUpload1.PostedFile.FileName;
            

                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();



                Microsoft.Office.Interop.Excel.Workbook workbook;

                Microsoft.Office.Interop.Excel.Worksheet worksheet;



                object oMissing = System.Reflection.Missing.Value;//相当null



                workbook = excel.Workbooks.Open(savePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);



                worksheet = (Worksheet)workbook.Worksheets[1];



                int rowCount = worksheet.UsedRange.Rows.Count;

                int colCount = worksheet.UsedRange.Columns.Count;



                Microsoft.Office.Interop.Excel.Range range1;



                System.Data.DataTable dt = new System.Data.DataTable();

              

                for (int i = 0; i < colCount; i++)
                {
                    
                    //range1 = worksheet.get_Range(worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]);
                    range1 = worksheet.Range[worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]];

                    dt.Columns.Add(range1.Value2.ToString());

                }

                for (int j = 1; j < rowCount; j++)
                {

                    DataRow dr = dt.NewRow();

                    for (int i = 0; i < colCount; i++)
                    {

                        //range1 = worksheet.get_Range(worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]);
                        range1 = worksheet.Range[worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]];

                        dr[i] = range1.Value2.ToString();

                    }

                    dt.Rows.Add(dr);

                }

                //dataGridView1.DataSource = dt;

                excel.Quit();

 

posted @ 2013-07-15 19:00  千回  阅读(239)  评论(0编辑  收藏  举报