Templat Word mengacu pada dokumen yang memiliki struktur, konten, dan gaya yang telah dibuat sebelumnya. Pengguna hanya perlu menambah atau mengganti sedikit konten untuk membuat dokumen sendiri. Dalam artikel ini, saya akan memperkenalkan cara membuat dokumen Word dari templat secara terprogram dengan mengganti placeholder (string) dengan string atau gambar baru, menggunakan «Spire.Doc untuk .BERSIH".

Pradesain Templat di MS Word

Berikut ini adalah screenshot template yang dihasilkan oleh MS Word. String seperti “#nama#”, “#alamat#” adalah placeholder yang akan diganti dengan string baru. Placeholder “#photograph#” akan diganti dengan gambar. Ingatlah untuk menerapkan pemformatan (ukuran font, gaya font, perataan, dll.) ke placeholder sehingga konten baru dapat mewarisi pemformatan ini.

Tambahkan Referensi

Metode #1: Unduh Spire.Doc dan unzip paket di suatu tempat di disk Anda untuk menemukan folder “BIN”. Spire.Doc memiliki DLL yang dikompilasi untuk beberapa versi .NET Framework serta untuk .NET Core dan platform lainnya. Pilih DLL dari folder yang Anda perlukan dan tambahkan semuanya sebagai dependensi dalam proyek Anda.

Metode #2: Buat aplikasi .NET di Visual Studio Anda, dan instal Spire.Doc langsung melalui NuGet. Manajer paket NuGet akan secara otomatis menginstal versi yang benar yang sesuai dengan aplikasi Anda.

Ganti Placeholder di Templat Word di C# dan VB.NET

Langkah-langkah mengganti placeholder pada template Word menggunakan Spire.Doc for .NET adalah sebagai berikut.

  • Buat objek Dokumen.
  • Muat templat Word menggunakan metode Document.LoadFromFile().
  • Simpan placeholder dan string baru dalam kamus.
  • Ganti placeholder dengan string baru menggunakan metode Document.Replace(string matchString, string newValue, bool caseSensitive, bool whoord).
  • Ganti placeholder dengan gambar menggunakan metode khusus ReplaceTextWithImage(Dokumen dokumen, String stringToReplace, String imagePath).
  • Simpan dokumen ke file Word menggunakan metode Document.SaveToFile().

[C#]

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace ReplacePlaceholdersInWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();
            
            //Load the template
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
//Store the old strings -"placeholders" and new strings in a dictionary
            Dictionary<string, string> replaceDict = new Dictionary<string, string>();
            replaceDict.Add("#name#", "Kaila Smith");
            replaceDict.Add("#address#", "123 Michigan Street, Bloomfield, MI94141");
            replaceDict.Add("#telephone#", "537286");
            replaceDict.Add("#mail#", "[email protected]");
            replaceDict.Add("#nationality#", "United States");
            replaceDict.Add("#birth#", "July 12th, 1992");
            replaceDict.Add("#gender#", "Female");
  
            //Replace strings with new strings 
            foreach (KeyValuePair<string, string> kvp in replaceDict)
            {
                document.Replace(kvp.Key, kvp.Value, true, true);
            }
//Get the image path
            String imagePath = "C:\\Users\\Administrator\\Desktop\\photo.jpg";
//Replace string in the template with image
            ReplaceTextWithImage(document, "#photograph#", imagePath);
//Save doc file.  
            document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
            document.Close();
        }
//Replace string in a Word document with an image
        static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
        {
            TextSelection[] selections = document.FindAllString(stringToReplace, false, true);
            Image image = Image.FromFile(imagePath);
            int index = 0;
            TextRange range = null;
            foreach (TextSelection selection in selections)
            {              
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(image);
                range = selection.GetAsOneRange();
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);
            }
        }
    }
}

[VB.NET]

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System
Imports System.Collections.Generic
Imports System.Drawing
 
Namespace ReplacePlaceholdersInWord
    Class Program
        static void Main(string() args)
        {
            'Create a Document object
            Document document = New Document()
 
            'Load the template
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx")
 
            'Store the old strings -"placeholders" and new strings in a dictionary
            Dictionary<string, string> replaceDict = New Dictionary<string, string>()
            replaceDict.Add("#name#", "Kaila Smith")
            replaceDict.Add("#address#", "123 Michigan Street, Bloomfield, MI94141")
            replaceDict.Add("#telephone#", "537286")
            replaceDict.Add("#mail#", "[email protected]")
            replaceDict.Add("#nationality#", "United States")
            replaceDict.Add("#birth#", "July 12th, 1992")
            replaceDict.Add("#gender#", "Female")
 
            'Replace strings with new strings 
            foreach (KeyValuePair<string, string> kvp in replaceDict)
            {
                document.Replace(kvp.Key, kvp.Value, True, True)
            }
 
            'Get the image path
            String imagePath = "C:\\Users\\Administrator\\Desktop\\photo.jpg"
 
            'Replace string in the template with image
            ReplaceTextWithImage(document, "#photograph#", imagePath)
 
            'Save doc file.  
            document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx)
            document.Close()
        }
 
        'Replace string in a Word document with an image
        static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
        {
            TextSelection() selections = document.FindAllString(stringToReplace, False, True)
            Image image = Image.FromFile(imagePath)
            Integer index = 0
            TextRange range = Nothing
            foreach (TextSelection selection in selections)
            {              
                DocPicture pic = New DocPicture(document)
                pic.LoadImage(image)
                range = selection.GetAsOneRange()
                index = range.OwnerParagraph.ChildObjects.IndexOf(range)
                range.OwnerParagraph.ChildObjects.Insert(index, pic)
                range.OwnerParagraph.ChildObjects.Remove(range)
            }
        }
    End Class
End Namespace

Keluaran