GIAO DIỆN BLOG ĐƯỢC CHỈNH SỬA BỞI HUNG.PRO.VN

[VB.NET] Hướng dẫn lấy dữ liệu từ winform sang Microsoft word

[VB.NET] Hướng dẫn fill dữ liệu từ winform vào Microsoft word
Xin chào mọi người, bài viết này mình sẽ hướng dẫn mọi người một cách để FILL dữ liệu từ WINFORM sang MICROSOFT WORD một cách nhanh nhất, mà không phải copy rắc rối.


Chúng ta bắt đầu nhé.

Đầu tiên, các bạn cần cài đặt thư viện DocX.

Thư viện này có cung cấp 2 phiên bản: cá nhân và thương mại.

Nếu dùng cá nhân thì vẫn dùng bình thường nhé bạn.

FULL CODE.

Imports Xceed.Words.NET

Public Class Form1
    Private templatePath As String = "Template.docx"
    Private outputPath As String = "Output.docx"
    Private newImagePath As String = ""

    <Obsolete>
    Private Sub btnFillToWord_Click(sender As Object, e As EventArgs) Handles btnFillToWord.Click
        Try
            Dim document As DocX = DocX.Load(templatePath)

            document.ReplaceText("<sohopdong>", txtSoHopDong.Text.Trim())

            document.ReplaceText("<tenkhachhang>", txtTenKhachHang.Text.Trim())
            document.ReplaceText("<dienthoai>", txtDienThoai.Text.Trim())

            document.ReplaceText("<diachi>", txtDiaChi.Text.Trim())

            If newImagePath <> "" Then

                Dim placeholderParagraph = document.Paragraphs.FirstOrDefault(Function(p) p.Text.Contains("<hinhkhachhang>"))

                If placeholderParagraph IsNot Nothing Then

                    Dim img = document.AddImage(newImagePath)
                    Dim picture = img.CreatePicture()
                    picture.Width = 80
                    picture.Height = 100

                    placeholderParagraph.InsertPicture(picture)
                    document.ReplaceText("<hinhkhachhang>", "")

                Else
                    MessageBox.Show("The picture placeholder was not found in the document.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                End If
            End If


            document.SaveAs(outputPath)

            MessageBox.Show("File Word đã được tạo thành công tại:" & vbCrLf & outputPath, "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Process.Start(outputPath)
        Catch ex As Exception
            MessageBox.Show("Có lỗi xảy ra: " & ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        Dim dlg = New OpenFileDialog()
        If dlg.ShowDialog() = DialogResult.OK Then
            newImagePath = dlg.FileName
            PictureBox1.LoadAsync(newImagePath)
        End If

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


    End Sub
End Class

Như vậy đã hoàn thành, chúc các bạn thành công.

Nếu ai chưa rỏ thì có thể DOWNLOAD FULL SOURCE ở bên dưới về để tìm hiểu nhé.

3 nhận xét

  1. test comment
    1. test reply
    2. test reply