NEWS

[DEVEXPRESS] Hướng dẫn export data từ sqlserver vào file template excel có sẵn C# winform

[DEVEXPRESS] Hướng dẫn export data từ sqlserver vào file template excel có sẵn C# winform
Đăng bởi: Thảo Meo - Lượt xem: 11356 11:29:12, 23/05/2020EBOOK

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách sử dụng Spreadsheet để xuất dữ liệu từ DataTable Sqlserver vào mẫu template file excel có sẵn trong lập trình C# Winform.

[DEVEXPRESS] EXPORT DATA TO EXCEL TEMPLATE EXISTS C# WINFORM USING SPREADSHEET

Trong lập trình ứng dụng, khi các bạn muốn xuất dữ liệu từ Database ra file excel theo mẫu có sẵn của chúng ta đã thiết kế:

Trong mẫu đã có sẵn các thông tin:

  1. Tên công ty
  2. Logo công ty
  3. Định dạng format text theo yêu cầu của mình

Vậy khi xuất dữ liệu ra excel theo mẫu, sẽ làm cho người dùng ít phải thao tác chỉnh sửa hơn.

Các bạn nào có sử dụng phần mềm kế toán Misa thì cũng thấy người ta cũng xuất dữ liệu ra template excel giống vậy.

Ví dụ: mình có một mẫu template excel Danh sách sản phẩm như hình bên dưới đây:

template_excel_csharp

và ta có dữ liệu từ SQL Server như hình bên dưới được select từ bảng table Products trong database mẫu NORTHWND.

template_excel_demo

Và kết quả mong muốn của chúng ta sau khi đổ dữ liệu vào template thành công thì sẽ được kết quả như hình ảnh bên dưới:

export_template_excel_csharp

Full source code demo ứng dụng export data to template Excel C#:

using DevExpress.Export.Xl;
using DevExpress.Spreadsheet;
using DevExpress.XtraSpreadsheet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FillDataToTemplateExcel
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
            configDatabase.ConnectString();
        }

        
        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void btn_export_Click(object sender, EventArgs e)
        {
            SpreadsheetControl spreadsheetControl1 = new SpreadsheetControl();
            var dt = SQLHelper.ExecQueryDataAsDataTable("SELECT ProductID, ProductName, UnitPrice, UnitsInStock FROM dbo.Products");
            IWorkbook workbook = spreadsheetControl1.Document;
            workbook.LoadDocument("template.xlsx", DocumentFormat.Xlsx);
            Worksheet sheet = workbook.Worksheets[0];
            workbook.BeginUpdate();
            try
            {
                ExternalDataSourceOptions options = new ExternalDataSourceOptions() { ImportHeaders = true };
                // Bắt đầu ghi từ column thứ 7
                Table table = sheet.Tables.Add(dt, 7, 1, options);
                TableStyleCollection tableStyles = workbook.TableStyles;
                TableStyle tableStyle = tableStyles[BuiltInTableStyleId.TableStyleMedium2]; // Đổi style table ở đây

                // Apply the table style to the existing table.
                table.Style = tableStyle;

                table.Columns[0].Name = "Mã sản phẩm";
                table.Columns[1].Name = "Tên sản phểm";   
                table.Columns[2].Name = "Số lượng";
                table.Columns[3].Name = "Đơn giá";
                TableColumn subtotalColumn = table.Columns.Add();
                subtotalColumn.Name = "Thành tiền";
                subtotalColumn.Formula = "=[Số lượng] * [Đơn giá]";
                subtotalColumn.TotalRowFunction = TotalRowFunction.Sum;                
                table.ShowTotals = true;
                table.Columns[3].TotalRowLabel = "TỔNG CỘNG";
                table.Columns[0].TotalRowLabel = "";                
                subtotalColumn.DataRange.NumberFormat = "$#,##0.00";
                // sử dụng custom style
                //TableStyle customTableStyle = workbook.TableStyles.Add("testTableStyle");
                //TableStyleElement totalRowStyle = customTableStyle.TableStyleElements[TableStyleElementType.TotalRow];
                //customTableStyle.BeginUpdate();
                //totalRowStyle.Fill.BackgroundColor = Color.Green;
                //totalRowStyle.Font.Color = Color.White;
                //totalRowStyle.Font.Bold = true;
                //customTableStyle.EndUpdate();

                //table.Style = customTableStyle;

                // sheet.MergeCells(sheet.Range["B2764:G2764"]);

            }
            finally
            {
                workbook.EndUpdate();
            }

            spreadsheetControl1.SaveDocument("test.xlsx", DocumentFormat.Xlsx);
            Process.Start("test.xlsx");
        }
    }
}

Trong source code, trên mình sử dụng style ở đoạn code này, các bạn có thể thay đổi các kiểu style để đoạn code đó để test nhé:

tableStyles[BuiltInTableStyleId.TableStyleMedium2];

Các bạn có thể mở comment của mình bên dưới để có thể customize template theo yêu cầu của mình mong muốn.

Video demo ứng dụng:

Happy Coding :)

 

DOWNLOAD SOURCE

Tags: export excel c#spreadsheet devexpress c#export data to template excel exists c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Hướng dẫn export data từ sqlserver vào file template excel có sẵn C# winform
Đăng bởi: Thảo Meo - Lượt xem: 11356 11:29:12, 23/05/2020EBOOK