ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 2737|ตอบกลับ: 0

[VB.NET] การสร้างจดหมายเวียน หรือ Mail Merge ด้วยของฟรี Syncfusion

[คัดลอกลิงก์]

308

กระทู้

498

โพสต์

5971

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
5971



จดหมายเวียน หรือ Mail Merge คือการทำจดหมายหลายๆฉบับ โดยมีเนื้อความเหมือนกัน แต่มีชื่อและที่อยู่ของผู้รับที่ไม่เหมือนกันเท่านั้น ซึ่งแทนที่จะต้องพิมพ์จดหมายแต่ละฉบับสำหรับผู้รับแต่ละราย ก็เพียงแต่สร้างไฟล์ที่เก็บชื่อและที่อยู่ไว้ก่อน และสร้างไฟล์ที่เก็บข้อความในจดหมายไว้อีกไฟล์หนึ่งแยกจากกัน แล้วจึงนำข้อมูลทั้งสองไปรวมหรือผนวกกัน ... โค้ดชุดนี้จะใช้ VB.NET เป็นพระเอกในการควบคุมการทำงานของโปรแกรม เพื่อให้สามารถเลือกพิมพ์รายการที่ต้องการ หรือ พิมพ์ออกไปได้ทั้งหมดพร้อมกัน โดยใช้ฐานข้อมูล MS Access เก็บรายการลูกค้า/สมาชิก และใช้ของฟรี Syncfusion.DocIO เป็นตัวกลางในการสร้างจดหมายเวียน เพื่อส่งออกไปแสดงผลยัง MS Word ...

ดาวน์โหลดของฟรี Syncfusion Community License ...

ขั้นตอนการทำเอกสารจดหมายเวียน (Mail Merge) บน MS Word ...
- เลือก Data Source


- เบราซ์หาไฟล์ฐานข้อมูล


- การสร้าง Merge Field


- การสร้างกลุ่มการแสดงผล (BeginGroup) เพื่อแสดงผลตามรายการที่เลือกมาพิมพ์ (เริ่มจาก Insert Tab)


- การปิดกลุ่มการแสดงผล ... ทำเหมือนกับ BeginGroup แต่เปลี่ยนชื่อเป็น EndGroup


- การบันทึกไฟล์ต้นแบบ (Template) เพื่อนำไปใช้งานใน VB.NET


Add References ... Syncfusion.DocIO.Base.DLL


มาดูโค้ดต้นฉบับกันเถอะ ...
  1. Imports System.Data
  2. Imports System.Data.OleDb
  3. Imports Syncfusion.DocIO
  4. Imports Syncfusion.DocIO.DLS

  5. Public Class frmMailMerge
  6.     '// Declare variable one time but use many times.
  7.     Dim Conn As OleDbConnection
  8.     Dim Cmd As OleDbCommand
  9.     Dim DS As DataSet
  10.     Dim DR As OleDbDataReader
  11.     Dim DA As OleDbDataAdapter
  12.     Dim strSQL As String '// Major SQL

  13.     Dim MyPath As String = GetPath(Application.StartupPath)

  14.     Private Sub frmMailMerge_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  15.         Me.Dispose()
  16.         GC.SuppressFinalize(Me)
  17.         Application.Exit()
  18.     End Sub

  19.     '// Start Here.
  20.     Private Sub frmMailMerge_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  21.         '// Create MailMerge Folder if doesn't exist. (Keep Output Mail Merge.)
  22.         If (Not System.IO.Directory.Exists(MyPath & "MailMerge")) Then System.IO.Directory.CreateDirectory(MyPath & "MailMerge")
  23.         '//
  24.         If Not ConnectDataBase() Then Me.Close()
  25.         Call SetupDGVData(dgvData)
  26.         Call RetrieveData()
  27.     End Sub

  28.     Private Function ConnectDataBase() As Boolean
  29.         Try
  30.             Dim strConn As String = _
  31.                     "Provider = Microsoft.ACE.OLEDB.12.0; " & _
  32.                     "Data Source = " & MyPath & "SampleDB.accdb"
  33.             Conn = New OleDb.OleDbConnection(strConn)
  34.             Conn.Open()
  35.             If Conn.State = ConnectionState.Open Then Conn.Close()
  36.             ' Return
  37.             Return True
  38.         Catch ex As Exception
  39.             MessageBox.Show(ex.Message)
  40.             Return False
  41.         End Try
  42.     End Function

  43.     Public Function GetPath(ByVal MyPath As String) As String
  44.         '/ Replace folder.
  45.         MyPath = MyPath.ToLower.Trim.Replace("\bin\debug", "").Replace("\bin\release", "")
  46.         '// If not found folder then put the \ (BackSlash ASCII Code = 92) at the end.
  47.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  48.         Return MyPath
  49.     End Function 'GetPath

  50.     ' / --------------------------------------------------------------------------------
  51.     Private Sub RetrieveData()
  52.         strSQL = _
  53.             " SELECT Customer.CustomerPK, Customer.CustomerID, Customer.FullName, Customer.Address, Customer.Amphur, Province.ProvinceName, Customer.PostCode " & _
  54.             " FROM Customer INNER JOIN Province ON Customer.ProvinceFK = Province.ProvincePK ORDER BY CustomerPK "
  55.         Try
  56.             If Conn.State = ConnectionState.Closed Then Conn.Open()
  57.             Cmd = New OleDbCommand
  58.             With Cmd
  59.                 .Connection = Conn
  60.                 .CommandText = strSQL
  61.             End With
  62.             DR = Cmd.ExecuteReader
  63.             Dim i As Long = dgvData.RowCount
  64.             While DR.Read
  65.                 With dgvData
  66.                     .Rows.Add(i)
  67.                     .Rows(i).Cells(0).Value = DR.Item("CustomerPK").ToString
  68.                     .Rows(i).Cells(1).Value = DR.Item("Fullname").ToString
  69.                     .Rows(i).Cells(2).Value = DR.Item("Address").ToString
  70.                     .Rows(i).Cells(3).Value = DR.Item("Amphur").ToString
  71.                     .Rows(i).Cells(4).Value = DR.Item("ProvinceName").ToString
  72.                     .Rows(i).Cells(5).Value = DR.Item("PostCode").ToString
  73.                 End With
  74.                 i += 1
  75.             End While
  76.             lblRecordCount.Text = "[Total : " & dgvData.RowCount & " records]"
  77.             DR.Close()
  78.             Cmd.Dispose()
  79.             Conn.Close()

  80.         Catch ex As Exception
  81.             MessageBox.Show(ex.Message)
  82.         End Try
  83.     End Sub

  84.     ' / --------------------------------------------------------------------------------
  85.     '// Initialize DataGridView @Run Time
  86.     Private Sub SetupDGVData(ByRef DGV As DataGridView)
  87.         With dgvData
  88.             .RowHeadersVisible = False
  89.             .AllowUserToAddRows = False
  90.             .AllowUserToDeleteRows = False
  91.             .AllowUserToResizeRows = False
  92.             .MultiSelect = False
  93.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  94.             .ReadOnly = True
  95.             .Font = New Font("Tahoma", 9)
  96.             ' Columns Specified
  97.             .Columns.Add("CustomerPK", "CustomerPK")
  98.             .Columns.Add("Fullname", "Full Name")
  99.             .Columns.Add("Address", "Address")
  100.             .Columns.Add("Amphur", "Amphur")
  101.             .Columns.Add("ProvinceName", "Province Name")
  102.             .Columns.Add("PostCode", "PostCode")
  103.             '// Select Print.
  104.             Dim chkPrint As New DataGridViewCheckBoxColumn
  105.             .Columns.Add(chkPrint)
  106.             chkPrint.HeaderText = "Select Print"
  107.             chkPrint.Name = "chkPrint"
  108.             With .Columns("chkPrint")
  109.                 .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
  110.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
  111.             End With
  112.             '// Hidden Columns
  113.             .Columns(0).Visible = False
  114.             ' Autosize Column
  115.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  116.             '.AutoResizeColumns()
  117.             '// Even-Odd Color
  118.             .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
  119.             ' Adjust Header Styles
  120.             With .ColumnHeadersDefaultCellStyle
  121.                 .BackColor = Color.Navy
  122.                 .ForeColor = Color.Black ' Color.White
  123.                 .Font = New Font("Tahoma", 9, FontStyle.Bold)
  124.             End With
  125.         End With
  126.     End Sub

  127.     '// Toggle Checked Or UnChecked.
  128.     Private Sub dgvData_CellContentClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellContentClick
  129.         '// Column Index = 6
  130.         If dgvData.Columns(e.ColumnIndex).Name = "chkPrint" Then
  131.             Dim isChecked As Boolean = dgvData.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
  132.             If isChecked = False Then
  133.                 dgvData.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = True
  134.             Else
  135.                 dgvData.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False
  136.             End If
  137.         End If
  138.     End Sub

  139.     '// Get DataTable.
  140.     Private Function GetDataTable(ByVal Sql As String) As DataTable
  141.         DS = New DataSet
  142.         If Conn.State = ConnectionState.Closed Then Conn.Open()
  143.         DA = New OleDbDataAdapter(Sql, Conn)
  144.         DA.Fill(DS)
  145.         DA.Dispose()
  146.         Conn.Close()
  147.         Dim table As System.Data.DataTable = DS.Tables(0)
  148.         '// Sets table name as Customers for template merge field reference.
  149.         table.TableName = "Customer"
  150.         Return table
  151.     End Function

  152.     '// Print All Customers.
  153.     Private Sub btnMailAll_Click(sender As System.Object, e As System.EventArgs) Handles btnMailAll.Click
  154.         Dim document As New WordDocument(MyPath & "Template" & "GroupCustomer.docx")
  155.         '/ Gets the data table
  156.         Dim table As DataTable = GetDataTable("SELECT * FROM Customer ORDER BY CustomerPK")
  157.         '/ Executes Mail Merge with groups
  158.         document.MailMerge.ExecuteGroup(table)
  159.         '/ Saves and closes the WordDocument instance
  160.         '/ Folder--> ProjectName\Document
  161.         Dim dtFileName As String = Format(Now, "ddMMyyyy-hhmmss")
  162.         document.Save(MyPath & "MailMerge" & dtFileName & ".docx")
  163.         document.Close()
  164.         '// Open MS Word with Mail Merge.
  165.         Process.Start(MyPath & "MailMerge" & dtFileName & ".docx")
  166.     End Sub

  167.     '// Print Only Select Customers.
  168.     Private Sub btnMailSelect_Click(sender As System.Object, e As System.EventArgs) Handles btnMailSelect.Click
  169.         Dim chkCount As Integer
  170.         Dim Customers As New List(Of Customer)()
  171.         For i = 0 To dgvData.RowCount - 1
  172.             If CType(dgvData.Rows(i).Cells(6).Value, Boolean) = True Then
  173.                 chkCount += 1
  174.                 '// Keep data for print into Customer List. (CustomerPK, Fullname)
  175.                 Customers.Add(New Customer(dgvData.Rows(i).Cells(0).Value, dgvData.Rows(i).Cells(1).Value.ToString))
  176.             End If
  177.         Next
  178.         '// Start Print.
  179.         If chkCount = 0 Then
  180.             MessageBox.Show("คุณไม่ได้เลือกทำรายการพิมพ์", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  181.             Return

  182.             '// Print only the selected columns.
  183.         Else
  184.             Dim document As New WordDocument(MyPath & "Template" & "GroupCustomer.docx")
  185.             Dim table As New MailMergeDataTable("Customer", Customers)
  186.             document.MailMerge.ExecuteGroup(table)
  187.             '/ Folder--> ProjectName\MailMerge
  188.             Dim dtFileName As String = Format(Now, "ddMMyyyy-hhmmss")
  189.             document.Save(MyPath & "MailMerge" & dtFileName & ".docx", FormatType.Docx)
  190.             document.Close()
  191.             Process.Start(MyPath & "MailMerge" & dtFileName & ".docx")
  192.         End If
  193.         '// Clear Selection
  194.         For i = 0 To dgvData.RowCount - 1
  195.             If CType(dgvData.Rows(i).Cells(6).Value, Boolean) = True Then
  196.                 dgvData.Rows(i).Cells(6).Value = False
  197.             End If
  198.         Next
  199.     End Sub

  200. End Class
คัดลอกไปที่คลิปบอร์ด

ส่วนของ Customer Class เพื่อส่งไปให้กับ Array List เก็บรายการที่ต้องการพิมพ์จดหมายเวียน ...
  1. Public Class Customer

  2.     Private m_CustomerPK As Long
  3.     Public Property CustomerPK() As Long
  4.         Get
  5.             Return m_CustomerPK
  6.         End Get
  7.         Set(ByVal value As Long)
  8.             m_CustomerPK = value
  9.         End Set
  10.     End Property

  11.     Private m_CustomerID As String
  12.     Public Property CustomerID() As String
  13.         Get
  14.             Return m_CustomerID
  15.         End Get
  16.         Set(value As String)
  17.             m_CustomerID = value
  18.         End Set
  19.     End Property

  20.     Private m_Fullname As String
  21.     Public Property Fullname() As String
  22.         Get
  23.             Return m_Fullname
  24.         End Get
  25.         Set(value As String)
  26.             m_Fullname = value
  27.         End Set
  28.     End Property

  29.     Private m_Address As String
  30.     Public Property Address() As String
  31.         Get
  32.             Return m_Address
  33.         End Get
  34.         Set(ByVal value As String)
  35.             m_Address = value
  36.         End Set
  37.     End Property

  38.     Private m_ProvinceName As String
  39.     Public Property ProvinceName() As String
  40.         Get
  41.             Return m_ProvinceName
  42.         End Get
  43.         Set(ByVal value As String)
  44.             m_ProvinceName = value
  45.         End Set
  46.     End Property

  47.     Private m_PostCode As String
  48.     Public Property PostCode() As String
  49.         Get
  50.             Return m_PostCode
  51.         End Get
  52.         Set(ByVal value As String)
  53.             m_PostCode = value
  54.         End Set
  55.     End Property

  56.     Private m_PictureName As String
  57.     Public Property PictureName() As String
  58.         Get
  59.             Return m_PictureName
  60.         End Get
  61.         Set(ByVal value As String)
  62.             m_PictureName = value
  63.         End Set
  64.     End Property

  65.     '// หากต้องการใช้งานฟิลด์อื่นๆ ต้องเพิ่มเข้ามาต่อท้ายในส่วนนี้ด้วย
  66.     Public Sub New(CustomerPK As Integer, Fullname As String)
  67.         Me.CustomerPK = CustomerPK
  68.         Me.Fullname = Fullname
  69.     End Sub

  70. End Class
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดฉบับเต็ม VB.NET (2010) ได้ที่นี่ ...

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-3-28 16:59 , Processed in 0.216781 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้