1024programmer Asp.Net .NET uses AsposeWord to dynamically export data to Word through Word templates

.NET uses AsposeWord to dynamically export data to Word through Word templates

.NET uses AsposeWord to dynamically export data to Word through Word templates

@

Table of Contents

  • First take a look at the overall effect of the export (as shown below). The marked areas are dynamically generated through the background:
  • 1. First Create a table template in Word
  • 1.1. Parameter creation method (Word and WPS)
    • 1.1.1. Creation of Word fields in Office
      • 1.1.1.1. Select Specified cell -> Click “Insert” in the header toolbar -> Select “Document Parts” -> Select “Field”;
      • 1.1.1.2. In the “Select Field” on the left Find “Mergefield” -> fill in the variable name in the domain name (Note: the filled in domain name needs to be the same as the field in the field name array defined in the background, so that the corresponding data will be filled); li>
      • 1.1.1.3. List creation domain
    • 1.1.2. Creation of WPS domain in Office
      • 1.1.2.1. Select the specified Cell -> Click “Insert” in the header toolbar -> Select “Document Parts” -> Select “Field”;
      • 1.1.2.2. Find “Select Field” on the left Mail Merge” -> Fill in the variable name in the field code: for example: (MERGEFIELD Textdwmc) (Note: The filled in domain name needs to be the same as the field in the field name array defined in the background, so that the corresponding data will be filled);
  • 2. Add related DLL files
    • 2.1. Add related DLL files
      • 2.1.1. Right-click the project -> Manage NuGet Packages
      • 2.1.2. Browse and search in the Manage NuGet Packages: Aspose.Words (Note: Be sure to select 21.8.0 version, this version can remove the watermark, I have not tried other higher versions yet ( ̄▽ ̄)~*) Just click to install!
  • 3. Write code (backend .NET code takes VS 2019 as an example)
    • 3.1. Define public fields (Note: The defined array field must be the same as the domain name in the Word template)
    • 3.2. Core method of Word template operation
    • 3.3. Generated through Word template New file
    • 3.4, calling method
    • 3.5, .NET file download
      • 3.5.1, ASP.NET file download
      • 3.5. 2. How to download ASP.NET MVC

First, take a look at the overall effect of the export (as shown below). The marked areas are dynamically generated through the background. :

Rendering

1. First, create a table template in Word

Word Template

1.1. Parameter creation method (Word and WPS)

1.1.1. Creation of word domain in office

1.1.1.1. Select the specified cell-> Click the header “Insert” in the toolbar -> select “Document Parts” -> select “Field”;

Office add domain

1.1.1.2. Find “Mergefield” in the “Select Field” on the left -> fill in the variable name in the domain name ( Note: the domain name filled in needs to be the same as the field in the field name array defined in the background , so that the corresponding data will be filled in);

Variable name

1.1.1.3, list creation domain

There is a list area; loop insertion is required. Loop generation area insertion: Enter the start identifier: TableStart:UserList. The UserList here should correspond to dt.TableName = “UserList”, so that the data in the DataTable will be filled in the table accordingly.
Loop area

Enter other fields in the DataTable.
Other fields

Finally, remember to also enter an end identifier: “”TableEnd:UserList””””Last Column Name”” and delete the redundant lines below. When the WORD template is generated, it will be automatically filled downwards.

Since then, the Word table template has been created!

1.1.2, Creation of WPS domain in Office

1.1.2.1,th);
doc.MailMerge.Execute(fieldNames, fieldValues);
//Put the DataTable type data we obtained: EduDataTable into the doc method for processing
if (dt.Rows.Count > 0 && dt!=null)
{
doc.MailMerge.ExecuteWithRegions(dt);
}
//Get the download address
String StrVisitURL = saveFold + fileName;
//Merge template, equivalent to page rendering
doc.MailMerge.Execute(new[] { “PageCount” }, new object[] { doc.PageCount });
//Save the merged document
doc.Save(outputPath);
return StrVisitURL;
}
catch(Exceptioner)
{
returner.Message;
}
}

///

/// Load monitoring, used to remove watermarks
///

public static void removeWatermark()
{
new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(“PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUb z4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0 byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4yMDA2MDIwMTI2MzM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3N jAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9k dWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+OTM2ZTVmZDEtODY2Mi00YWJmLTk1YmQtYzhkYzBmNT NhZmE2PC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjEwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvb j4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+ CiAgPFNpZ25hdHVyZT5wSkpjQndRdnYxV1NxZ1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhEejFiK1JIWTBuQkh1 SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJvU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4 =”)));
}
}
}

3.3. Generate new files through Word template

/// 
         /// Based on basic information of WORD template
         /// 
         /// The superior ID of the sub-data that needs to be looped
         /// Returns the completed file download path
         public static string GetWordEvent(string id)
         {
             try
             {
             //Here is the instantiated Model. If the project already has an encapsulated method of querying database information, you can directly use the parameter "id" to perform dynamic data query.
                 memberUnit member = new memberUnit();
                 member.id = "202204291157458529";
                 member.Textdwmc = "Changsha Jieshu Co., Ltd.";
                 member.Textdwdz = "Governor of Hunan";
                 member.Textfrdb =null;
                 member.Texthyxm = "gows";
                 member.Textmz = "汉";
                 member.Radioxb = "Male";
                 member.Textsfz = "4302685556951366";
                 member.Textdp = "Party Member";
                 member.Textlxdh = "175125956569";
                 member.Textwhcd = "High School";
                 member.Textgryx = "[email protected]";
                 member.Texthyxz = "wu";
                 member.Textqyrs = "1444";
                 member.Textjxdz = "Hunan";
                 member.droprhxz = "Vice President";
                 member.Textrhsq = "Uh uh uh uh uh uh uh uh uh uh uh uh";
                 member.Radiostate = "Processed";

                 Object[] fieldValues ​​= new object[fieldNames.Length];
                 fieldValues[0] = member.Textdwmc;
                 fieldValues[1] = member.Textdwdz;
                 fieldValues[2] = member.Textfrdb;
                 fieldValues[3] = member.Texthyxm;
                 fieldValues[4] = member.Textmz;
                 fieldValues[5] = member.Radioxb;
                 fieldValues[6] = member.Textsfz;
                 fieldValues[7] = member.Textdp;
                 fieldValues[8] = member.Textlxdh;
                 fieldValues[9] = member.Textwhcd;
                 fieldValues[10] = member.Textgryx;
                 fieldValues[11] = member.Texthyxz;
                 fieldValues[12] = member.Textqyrs;
                 fieldValues[13] = member.Textjxdz;
                 fieldValues[14] = member.droprhxz;
                 fieldValues[15] = member.Textrhsq;
                 fieldValues[16] = member.Radiostate;
                 DataTable dt = new DataTable();
                
             #region /// Note: If there is no data similar to tables or lists in Word, it is not needed here, just delete it.

                 if (!string.IsNullOrEmpty(id))
                 {
                     string sql = " SELECT * FROM TABLE WHERE id='' ORDER BY id DESC ";
                     dt = getDataTable(sql);
                     //The UserList here is very important. It must correspond to the domain settings of the WORD template. It is not written casually. It will be used later.
                     dt.TableName = "UserList";
                 }

             #endregion
             	
                 string StrVisitURL = WordModelEvent.ExpertWordToModel("template", member.Textdwmc, fieldNames, fieldValues, dt);
                 dt.Dispose();
                 return StrVisitURL;
             }
             catch(Exceptioner)
             {
                 returner.Message;
             }
         }

         /// 
         /// Obtain DataTable through SQL
         /// 
         /// sql query statement
         /// Your data connection string
         /// 
         private static DataTable getDataTable(string sql, string ConnectionString = "")
         {
             SqlConnection cn = new SqlConnection(ConnectionString);
             SqlDataAdapter da = new SqlDataAdapter(sql, cn);
             DataTable ds = new DataTable();
             da.Fill(ds);
             cn.Dispose();
             return ds;
         }
 

3.4. Calling method

string url= GetWordEvent("");
 

3.5, .NET file download

3.5.1, ASP.NET file download

/// 
        ///Character stream download method
        /// 
        /// The name generated by downloading the file
        /// Download file path
        /// 
         public void DownloadFile(string fileName, string fPath)
         {
             string filePath = Server.MapPath(fPath);//Path
             //Download the file in the form of character stream
             FileStream fs = new FileStream(filePath, FileMode.Open);
             byte[] bytes = new byte[(int)fs.Length];
             fs.Read(bytes, 0, bytes.Length);
             fs.Close();
             Response.ContentType = "application/octet-stream";
             //Notify the browser to download the file instead of opening it
             Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
             Response.BinaryWrite(bytes);
             Response.Flush();
             if (!string.IsNullOrEmpty(filePath)&& filePath!=".")
             {
                System.IO.File.Delete(filePath+"/"+fileName);//Delete the generated file after downloading it
             }
             Response.End();
         }
 

3.5.2, ASP.NET MVC download method

/// 
         /// How to download files
         /// 
         /// Absolute file path
         /// The file name received by the client
         /// 
         public static HttpResponseMessage Download(string path, string fileName)
         {
             var stream = File.OpenRead(path);
             HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
             try
             {
                 httpResponseMessage.Content = new StreamContent(stream);
                 httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                 if (!string.IsNullOrEmpty(fileName))
                 {
                     httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                     {
                         FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8),
                     };
                 }
                 if (!string.IsNullOrEmpty(filePath)&& filePath!=".")
                 {
                    System.IO.File.Delete(filePath+"/"+fileName);//Delete the generated file after downloading it
                 }
                 return httpResponseMessage;
             }
             catch
             {
                 stream.Dispose();
                 httpResponseMessage.Dispose();
                 throw;
             }
         }
 

This article comes from Blog Park, author: TomLucas, please indicate the original link when reprinting: https://www.cnblogs.com/lucasDC/p/17255910.html

��data is not needed here, just delete it

if (!string.IsNullOrEmpty(id))
{
string sql = ” SELECT * FROM TABLE WHERE id=” ORDER BY id DESC “;
dt = getDataTable(sql);
//The UserList here is very important. It must correspond to the domain settings of the WORD template. It is not written casually. It will be used later.
dt.TableName = “UserList”;
}

#endregion

string StrVisitURL = WordModelEvent.ExpertWordToModel(“template”, member.Textdwmc, fieldNames, fieldValues, dt);
dt.Dispose();
return StrVisitURL;
}
catch(Exceptioner)
{
returner.Message;
}
}

///

/// Obtain DataTable through SQL
///

/// sql query statement
/// Your data connection string
///
private static DataTable getDataTable(string sql, string ConnectionString = “”)
{
SqlConnection cn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
DataTable ds = new DataTable();
da.Fill(ds);
cn.Dispose();
return ds;
}

3.4. Calling method

string url= GetWordEvent("");
 

3.5, .NET file download

3.5.1, ASP.NET file download

/// 
        ///Character stream download method
        /// 
        /// The name generated by downloading the file
        /// Download file path
        /// 
         public void DownloadFile(string fileName, string fPath)
         {
             string filePath = Server.MapPath(fPath);//Path
             //Download the file in the form of character stream
             FileStream fs = new FileStream(filePath, FileMode.Open);
             byte[] bytes = new byte[(int)fs.Length];
             fs.Read(bytes, 0, bytes.Length);
             fs.Close();
             Response.ContentType = "application/octet-stream";
             //Notify the browser to download the file instead of opening it
             Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
             Response.BinaryWrite(bytes);
             Response.Flush();
             if (!string.IsNullOrEmpty(filePath)&& filePath!=".")
             {
                System.IO.File.Delete(filePath+"/"+fileName);//Delete the generated file after downloading it
             }
             Response.End();
         }
 

3.5.2, ASP.NET MVC download method

/// 
         /// How to download files
         /// 
         /// Absolute file path
         /// The file name received by the client
         /// 
         public static HttpResponseMessage Download(string path, string fileName)
         {
             var stream = File.OpenRead(path);
             HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
             try
             {
                 httpResponseMessage.Content = new StreamContent(stream);
                 httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                 if (!string.IsNullOrEmpty(fileName))
                 {
                     httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                     {
                         FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8),
                     };
                 }
                 if (!string.IsNullOrEmpty(filePath)&& filePath!=".")
                 {
                    System.IO.File.Delete(filePath+"/"+fileName);//Delete the generated file after downloading it
                 }
                 return httpResponseMessage;
             }
             catch
             {
                 stream.Dispose();
                 httpResponseMessage.Dispose();
                 throw;
             }
         }
 

This article comes from Blog Park, author: TomLucas, please indicate the original link when reprinting: https://www.cnblogs.com/lucasDC/p/17255910.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/net-uses-asposeword-to-dynamically-export-data-to-word-through-word-templates/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索