Kết xuất dữ liệu từ DataGridView ra file Excel

Kết xuất dữ liệu từ DataGridView ra file Excel

Khi bạn đã biết xử lý và hiển thị dữ liệu trên DataGridView, yêu cầu sau cùng là việc kết xuất dữ liệu ra tệp tin để in ấn hoặc lưu trữ. Kết xuất dữ liệu từ DataGridView ra tệp Excel là một trong những vấn đề được nhiều bạn quan tâm. Vậy bài viết này tôi trình bày cách để các bạn có thể làm được điều đó.

Giả sử bạn cần kết xuất dữ liệu ra 1 tệp Excel có định dạng như sau (Đơn giản để các bạn dễ hình dung):

Tệp Excel mẫu

Vậy bạn cần thiết kế giao diện Form tương tự như sau:

Giao diện mẫu

Lưu ý: Trong DataGridView trên có 1 cột mã đơn vị ẩn đi.

Việc hiển thị dữ liệu và thao tác trên DataGridView trong bài này mặc nhiên là bạn đã biết. Nếu chưa biết bạn có thể tham khảo các bài trước đó tôi đã trình bày để có được dữ liệu như trên.

Bây giờ khi tôi nhấn nút kết xuất thì dữ liệu trong DataGridView được chuyển qua tệp Excel. Vậy cách làm như sau:

Bước 1: Bạn cần thêm thư viện thao tác với Excel vào dự án, theo hướng dẫn sau:

Description: C:\Users\ADMIN\Pictures\New folder\DataGridView\wf-039.png

Lựa chọn thư viện Excel

Bước 2: Tạo 1 thư viện thao tác với tệp Excel (tạo thêm 1 file .cs có tên ExportToExcel).

Bạn xây dựng một phương thức Export với tham số truyền vào là 1 đối tượng DataTable chứa dữ liệu muốn kết xuất, có thể thêm các tham số SheetName (tên Sheet trong Excel) hay tiêu đề nếu có.

Bạn tham khảo code sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

namespace DemoDataGridView
{
    class ExportToExcel

    {

        public void Export(DataTable dt, string sheetName, string title)
        {

            //Tạo các đối tượng Excel

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

            Microsoft.Office.Interop.Excel.Workbooks oBooks;

            Microsoft.Office.Interop.Excel.Sheets oSheets;

            Microsoft.Office.Interop.Excel.Workbook oBook;

            Microsoft.Office.Interop.Excel.Worksheet oSheet;

            //Tạo mới một Excel WorkBook 

            oExcel.Visible = true;

            oExcel.DisplayAlerts = false;

            oExcel.Application.SheetsInNewWorkbook = 1;

            oBooks = oExcel.Workbooks;

            oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));

            oSheets = oBook.Worksheets;

            oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);

            oSheet.Name = sheetName;

            // Tạo phần đầu nếu muốn

            Microsoft.Office.Interop.Excel.Range head = oSheet.get_Range("A1", "C1");

            head.MergeCells = true;

            head.Value2 = title;

            head.Font.Bold = true;

            head.Font.Name = "Tahoma";

            head.Font.Size = "18";

            head.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

            // Tạo tiêu đề cột 

            Microsoft.Office.Interop.Excel.Range cl1 = oSheet.get_Range("A3", "A3");

            cl1.Value2 = "Mã đơn vị";

            cl1.ColumnWidth = 13.5;        

            Microsoft.Office.Interop.Excel.Range cl2 = oSheet.get_Range("B3", "B3");

            cl2.Value2 = "Tên đơn vị";

            cl2.ColumnWidth = 25.0;

            Microsoft.Office.Interop.Excel.Range cl3 = oSheet.get_Range("C3", "C3");

            cl3.Value2 = "Chức năng";

            cl3.ColumnWidth = 40.0;

            Microsoft.Office.Interop.Excel.Range rowHead = oSheet.get_Range("A3", "C3");

            rowHead.Font.Bold = true;

            // Kẻ viền

            rowHead.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;

            // Thiết lập màu nền

            rowHead.Interior.ColorIndex = 15;

            rowHead.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

            // Tạo mẳng đối tượng để lưu dữ toàn bồ dữ liệu trong DataTable,

            // vì dữ liệu được được gán vào các Cell trong Excel phải thông qua object thuần.

            object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];

            //Chuyển dữ liệu từ DataTable vào mảng đối tượng

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

            {

                DataRow dr = dt.Rows[r];

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

                {
                    arr[r, c] = dr[c];
                }
            }

            //Thiết lập vùng điền dữ liệu

            int rowStart = 4;

            int columnStart = 1;

            int rowEnd = rowStart + dt.Rows.Count - 1;

            int columnEnd = dt.Columns.Count;

            // Ô bắt đầu điền dữ liệu

            Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowStart, columnStart];

            // Ô kết thúc điền dữ liệu

            Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnEnd];

            // Lấy về vùng điền dữ liệu

            Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);

            //Điền dữ liệu vào vùng đã thiết lập

            range.Value2 = arr;

            // Kẻ viền

            range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;

            // Căn giữa cột STT

             Microsoft.Office.Interop.Excel.Range c3 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnStart];

            Microsoft.Office.Interop.Excel.Range c4 = oSheet.get_Range(c1,c3 );

             oSheet.get_Range(c3, c4).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;      
        }
    }
}

Bước 3: Bây giờ bạn chỉ việc gọi phương thức Export của lớp vừa xây dựng trên Form khi nhấn nút “Kết xuất ra Excel”

private void btnExportExcel_Click(object sender, EventArgs e)
{

        ExportToExcel excel = new ExportToExcel();
     // Lấy về nguồn dữ liệu cần Export là 1 DataTable
     // DataTable này mỗi bạn lấy mỗi khác. 
     // Ở đây tôi dùng BindingSouce có tên bs nên tôi ép kiểu như sau:
     // Bạn nào gán trực tiếp vào DataGridView thì ép kiểu DataSource của
     // DataGridView nhé 
        DataTable dt = (DataTable) bs.DataSource;
        excel.Export(dt, "Danh sach", "DANH SÁCH CÁC ĐƠN VỊ");

 }

Bước 4: Chạy và thử nghiệm bạn sẽ có kết quả tương tự sau:

Kết xuất dữ liệu từ DataGridView ra file Excel

Chúc bạn thành công!

Bạn thấy bài viết này như thế nào?: 
Average: 9.7 (6 votes)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
www.processing.org: Ngôn ngữ lập trình Processing

www.processing.org: Ngôn ngữ lập trình Processing

Processing là một ngôn ngữ lập trình hiện đại( ra đời năm 2001) cho phép lập trình các ứng dụng đồ họa trên môi trường Window, Linus, Mac Android và cả Web. Nếu bạn đã học C thì bạn có thể tự học Processing rất dễ dàng. Định dang một tập tin Processing là *pde

Mozilla sẽ giới thiệu điện thoại đầu tiên tại MWC 2012?

Mozilla sẽ giới thiệu điện thoại đầu tiên tại MWC 2012?

Mozilla đã hợp tác với LG nhằm cho ra mắt thiết bị di động đầu tiên của họ tại MWC 2012, một nguồn tin thân cận đã xác nhận với trang ExtremeTech.

Sandbox là gì?

Sandbox là gì?

"Sandbox" là gì mà các nhà phát triển dạo gần đây cứ liên tục đề cập đến? Sử dụng sandbox thế nào để tạo các ứng dụng xuất sắc hơn?

Công ty diệt chuột T&C

 

Diet con trung