.NET使用NPOI將數據導出/導入到Excel文件


      現在多數軟件都支持Excel的導入導出功能。因為將軟件中的數據導出到Excel中以后,財務專員就可以很方便的操作這些數據了。這樣可以節省很多工作量。並且,有數據導入功能可以使用戶啟用軟件時,不必花費時間就可以將上萬條記錄導如到軟件系統的數據庫中。大大減少了用戶的工作量,否則,用戶只能乖乖的一條條錄入了,如果錄入后沒保存,那就只能…..,大家懂的。

      今天咱們就來看下如何使用NPOI將程序中的數據導出的Excel文件。當然,將程序中的數據導出到Excel文件的方法有很多。但本人以為NPOI的最大優點就是即使你心愛的電腦沒有安裝office或者wps,那么依然可以正常導出。但是如果使用office組件類庫的方式,那么就不敢恭維了…

      言歸正傳,下面咱們一起來看下NPOI的偉大魅力吧!

      這里我帶領大家一起來寫個小例子,大家就會掌握NPOI的用法了。

      第1步:請大家新建一個Winfrom窗體應用程序命名為ExportOrImport,在窗體上放一個DataGridView控件和一個button控件。

      第二步:在當前項目中新建一個lib文件夾,並且將如下類庫復制到該文件夾下,然后右鍵點擊”引用”→”添加引用”,找到lib的各個dll文件,完成添加。

      第三步:在項目中引入如下命名空間:

        using NPOI.HSSF.UserModel;

        using NPOI.HPSF;

        using NPOI;

         using System.IO;

     第四步:通過ADO.NET從數據庫中讀取數據到DataGridView中

           string str = "data source=.;initial catalog=Myschool;uid=sa";

            SqlConnection con = new SqlConnection(str);

            string sql = "select studentno,studentname,address,birthday from student";

            SqlDataAdapter da = new SqlDataAdapter(sql,con);

            DataSet ds = new DataSet();

            da.Fill(ds, "Student");

            dataGridView1.DataSource = ds.Tables[0];

     第五步:將DataGridView中的數據導出到Excel文件中

          不多說了 ,直接上代碼

          //通過SaveFileDialog類彈出一個保存對話框

            SaveFileDialog sfd = new SaveFileDialog();

            //設置文件的保存類型,默認選中Excel文件

            sfd.Filter = "Excel文件|*.xls";

            //設置默認保存文件名稱

            sfd.FileName = "學生信息表";

            //如果用戶點擊了保存對話框的確定按鈕

            if (sfd.ShowDialog()==DialogResult.OK)

            {

                //獲取到Excel文件名

                string filename = sfd.FileName;

                //獲取學生列表

                //List<Student> list = dataGridView1.DataSource as List<Student>;

                //內存中創建一個空的Excel文件

               HSSFWorkbook workbook = new HSSFWorkbook();

              

                //在Excel文件上通過對HSSFSheet創建一個工作表

                HSSFSheet sheet = workbook.CreateSheet("students");

                //給工作表上添加一行

                HSSFRow row1 = sheet.CreateRow(0);

                //在添加的航上創建一個列

                HSSFCell cell1 = row1.CreateCell(0,HSSFCell.CELL_TYPE_STRING);

                //設置該列的值

                cell1.SetCellValue("學號");

 

                cell1 = row1.CreateCell(1, HSSFCell.CELL_TYPE_STRING);

                cell1.SetCellValue("學生姓名");

 

                cell1 = row1.CreateCell(2, HSSFCell.CELL_TYPE_STRING);

                cell1.SetCellValue("家庭住址");

 

                cell1 = row1.CreateCell(3, HSSFCell.CELL_TYPE_STRING);

                cell1.SetCellValue("出生日期");

                //遍歷dataGridView中的所有列,然后將列添加到Excel工作表中

                for (int i = 1; i <=dataGridView1.Rows.Count; i++)

                {

                    //設置字體

                    HSSFFont font = workbook.CreateFont();

                    //字體名稱

                    font.FontName = "華文行楷";

                    //設置字體大小

                    font.FontHeightInPoints = 25;

 

                    //設置列的樣式

                    HSSFCellStyle style1 = workbook.CreateCellStyle();

                    //設置列的背景色

                    style1.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.ORANGE.index;

                    //設置填充邊框樣式

                    style1.FillPattern = HSSFCellStyle.SOLID_FOREGROUND;

                    //設置字體顯示樣式

                    style1.SetFont(font);

 

                    HSSFCellStyle style2 = workbook.CreateCellStyle();

                    style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.YELLOW.index;

                    style2.FillPattern = HSSFCellStyle.SOLID_FOREGROUND;

                  

 

                    HSSFRow row = sheet.CreateRow(i);

                    HSSFCell cell = row.CreateCell(0, HSSFCell.CELL_TYPE_NUMERIC);

                    cell.CellStyle = style1;

                    cell.SetCellValue(dataGridView1.Rows[i - 1].Cells[0].Value.ToString());

 

                    cell = row.CreateCell(1,HSSFCell.CELL_TYPE_STRING);

                    cell.CellStyle = style1;

                    cell.SetCellValue(dataGridView1.Rows[i-1].Cells[1].Value.ToString());

 

                    cell = row.CreateCell(2, HSSFCell.CELL_TYPE_STRING);

                    cell.CellStyle = style2;

                    cell.SetCellValue(dataGridView1.Rows[i-1].Cells[2].Value.ToString());

 

                    cell = row.CreateCell(3, HSSFCell.CELL_TYPE_STRING);

                    cell.CellStyle = style2;

                    cell.SetCellValue(dataGridView1.Rows[i-1].Cells[3].Value.ToString());

                }

                using (FileStream fs=new FileStream(filename,FileMode.OpenOrCreate))

                {

                    //將內容寫入到硬盤中

                    workbook.Write(fs);

                }

                MessageBox.Show("導出成功!");

            }

     其實,還有一種思路,這里留給大家去思考。

      接下來咱們看下如何將一個已經存在的Excel文件導入到DataGridView中。

      由於上面對導出做了詳細的分析,而導入只是一個逆向的過程,這里就直接看代碼了。

       void InitializeWorkbook(string path)

        {

            //read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.

            //book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added.

            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))

            {

                hssfworkbook = new HSSFWorkbook(file);

            }

        }

        DataSet ds = new DataSet();

        void ConvertToDataTable()

        {

            HSSFSheet sheet = hssfworkbook.GetSheetAt(0);

            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

           

            DataTable dt = new DataTable();

            for (int j = 0; j < 5; j++)

            {

                dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());

            }

 

            while (rows.MoveNext())

            {

                HSSFRow row = (HSSFRow)rows.Current;

                DataRow dr = dt.NewRow();

 

                for (int i = 0; i < row.LastCellNum; i++)

                {

                    HSSFCell cell = row.GetCell(i);

                    if (cell == null)

                    {

                        dr[i] = null;

                    }

                    else

                    {

                        dr[i] = cell.ToString();

                    }

                }

                dt.Rows.Add(dr);

            }

            ds.Tables.Add(dt);

        }

        //從Excel導入

        private void button2_Click(object sender, EventArgs e)

        {

            InitializeWorkbook("學生信息表.xls");

            ConvertToDataTable();

 

           dgvexport.DataSource= ds.Tables[0];

        }

     好了,就寫到這里吧!希望能對大家有所幫助。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM