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

 
Microsoft thắt chặt cấp phép bản quyền Windows 8?

Microsoft thắt chặt cấp phép bản quyền Windows 8?

Một loạt các slide trình diễn bị rò rỉ trên mạng đã tiết lộ thông tin về OEM Activation mới trên Windows 8 được thiết kế để gây khó khăn cho việc kích hoạt bản quyền bất hợp pháp trong hệ điều hành mới của Microsoft.

How To Get Facebook For Android Phones

How To Get Facebook For Android Phones

It may look like a very simple task; browsing through the Android market to get an app that suits you, but the reality is its not.

Thủ thuật đếm total Number cho Disqus Comments trong Page in Drupal 7

Thủ thuật đếm total Number cho Disqus Comments trong Page in Drupal 7

On a recent project I had to show the total number of comments posted using Disqus for each node on a page. What the page did was loop through a bunch of nodes and render the teaser view of each node.

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

 

Diet con trung