把Excel数据填充word模板生成多份word文档

有些事情,你想记得的就会记得。有些事情,你想忘记的就会忘记,如果忘记不了,那就不要忘记了,因为忘记是不需要努力的。


Model_Car.cs代码

  public class Model_Car
    {
        public string PartyA { get; set; }
        public string PartyB { get; set; }
        public string Aidentity { get; set; }
        public string Bidentity { get; set; }
        public string Asinger { get; set; }
        public string Bsinger { get; set; }

    }

ExcelHelper.cs代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Aspose.Cells;

namespace ReplaceTest
{
    public class ExcelHelper
    {
        #region 数据导入
        public static DataTable ExeclToDataTable(string Path)
        {
            try
            {
                DataTable dt = new DataTable();
                Aspose.Cells.Workbook workbook = new Workbook();
                workbook.Open(Path);
                Worksheets wsts = workbook.Worksheets;
                for (int i = 0; i < wsts.Count; i++)
                {
                    Worksheet wst = wsts[i];
                    int MaxR = wst.Cells.MaxRow;
                    int MaxC = wst.Cells.MaxColumn;
                    if (MaxR > 0 && MaxC > 0)
                    {
                        dt = wst.Cells.ExportDataTableAsString(0, 0, MaxR + 1, MaxC + 1, true);
                    }
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static DataSet ExeclToDataSet(string Path)
        {
            try
            {
                DataTable dt = new DataTable();
                Aspose.Cells.Workbook workbook = new Workbook();
                workbook.Open(Path);
                Worksheets wsts = workbook.Worksheets;
                for (int i = 0; i < wsts.Count; i++)
                {
                    Worksheet wst = wsts[i];
                    int MaxR = wst.Cells.MaxRow;
                    int MaxC = wst.Cells.MaxColumn;
                    if (MaxR > 0 && MaxC > 0)
                    {
                        dt = wst.Cells.ExportDataTableAsString(0, 0, MaxR + 1, MaxC + 1, true);
                    }
                }
                //SqlDataAdapter adapter = null;
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                //adapter.Fill(dt);
                return ds;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion
    }
}

WordHelper.cs代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Aspose.Cells;
using Aspose.Words;

namespace ReplaceTest
{
    public class WordHelper
    {
        #region 导出Word
        public static string ModelToWord(Model_Car car,string path,int num)
        {
            try
            {
                Document doc = new Document(path);
                DocumentBuilder builder = new DocumentBuilder(doc);

                foreach (System.Reflection.PropertyInfo p in car.GetType().GetProperties())
                {
                    builder.MoveToBookmark(p.Name);
                    builder.Write(p.GetValue(car,null).ToString());
                }
                doc.Save(System.AppDomain.CurrentDomain.BaseDirectory + string.Format("OutFile/car{0}协议书By书签.doc", num));
                return "OK";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
       
        #endregion
    }
}

Index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="ReplaceTest.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:Button ID="btnConvert" runat="server" Text="转换" OnClick="btnConvert_Click" />

        </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ReplaceTest
{
    public partial class Index : System.Web.UI.Page
    {
        private const string pathDirectory = "~/DataFile/";
        private string excelfileName = "Buyer.xlsx";
        private string docfileName = "car协议书.doc";
        private string docfileName1 = "carByProperty协议书.doc";
        List<Model_Car>  list=new List<Model_Car>();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnConvert_Click(object sender, EventArgs e)
        {
            try
            {
             
                if (!Directory.Exists(Server.MapPath(pathDirectory)))
                {
                    //若文件目录不存在 则创建
                    Directory.CreateDirectory(Server.MapPath(pathDirectory));
                }
                string fullname = pathDirectory + excelfileName;
                string fullpath = Server.MapPath(fullname);
                DataTable inputdt = ExcelHelper.ExeclToDataTable(fullpath);


                for (int i = 0; i < inputdt.Rows.Count; i++)
                {
                    Model_Car mCar = new Model_Car();
                    mCar.PartyA = inputdt.Rows[i][0].ToString().Replace("\"", "").Trim();
                    mCar.PartyB = inputdt.Rows[i][1].ToString().Trim();
                    mCar.Aidentity = inputdt.Rows[i][2].ToString().Trim();
                    mCar.Bidentity = inputdt.Rows[i][3].ToString().Trim();
                    mCar.Asinger = inputdt.Rows[i][4].ToString().Trim();
                    mCar.Bsinger = inputdt.Rows[i][5].ToString().Trim();
                    list.Add(mCar);
                }

                string docfullpath = Server.MapPath(pathDirectory + docfileName1);
                for (int i = 0; i < list.Count; i++)
                {
                    WordHelper.ModelToWord(list[i], docfullpath, i);
                }

            }
            catch (Exception ex)
            {
            }
        }
    }
}

方法二生成多份word文档:

 public partial class Index : System.Web.UI.Page
    {
        private const string pathDirectory = "~/DataFile/";
        private string excelfileName = "Buyer.xlsx";
        private string docfileName = "car协议书.doc";
        List<Model_Car>  list=new List<Model_Car>();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Directory.Exists(Server.MapPath(pathDirectory)))
                {
                    //若文件目录不存在 则创建
                    Directory.CreateDirectory(Server.MapPath(pathDirectory));
                }
                string fullname = pathDirectory + excelfileName;
                string fullpath = Server.MapPath(fullname);
                DataTable inputdt = ExcelHelper.ExeclToDataTable(fullpath);


                string docfullpath = Server.MapPath(pathDirectory + docfileName);

                WordHelper.DtToWord(inputdt, docfullpath);
             
            }
            catch (Exception ex)
            {
            }
        }
    }
  public static void DtToWord(DataTable inputdt, string docfullpath)
        {
            
            for (int i = 0; i < inputdt.Rows.Count; i++)
            {
                Document doc = new Document(docfullpath);
                DocumentBuilder builder = new DocumentBuilder(doc);
                for (int j = 0; j <  inputdt.Columns.Count; j++)
                {
                    string Cellvalue = inputdt.Rows[i][j].ToString().Trim();
                    builder.MoveToBookmark(inputdt.Columns[j].ColumnName);
                    builder.Write(Cellvalue);
                }
                doc.Save(System.AppDomain.CurrentDomain.BaseDirectory + string.Format("OutFile/car{0}协议书By书签.doc", i));
            
            }

        }

        /// <summary>
        /// 根据datatable获得列名
        /// </summary>
        /// <param name="dt">表对象</param>
        /// <returns>返回结果的数据列数组</returns>
        public static string[] GetColumnsByDataTable(DataTable dt)
        {
            string[] strColumns = null;


            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                strColumns = new string[columnNum];
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strColumns[i] = dt.Columns[i].ColumnName;
                }
            }
            return strColumns;
        }


项目及文档结构:

这里写图片描述


这里写图片描述


这里写图片描述


运行结果

这里写图片描述

这里写图片描述

### 回答1: 将Excel中的数据按照Word模板生成Word文档可以通过使用代码或者使用Python等编程语言来实现。 使用代码的方法是,首先打开ExcelWord软件,然后在Excel中选择需要导出到Word数据范围,点击开发工具栏中的"视图代码"按钮,将打开编辑器。在编辑器中,编写代码来读取Excel中的数据,并将数据插入到Word模板中的相应位置。最后保存并运行该,即可生成Word文档。 另一种方法是使用Python等编程语言来实现,首先需要安装相应的库文件,如openpyxl和python-docx。然后在Python中编写代码,使用openpyxl库读取Excel中的数据,并使用python-docx库创建Word文档并将数据插入到文档中的相应位置。最后保存生成Word文档。 无论是使用代码还是编程语言,都需要明确Excel数据的格式和Word模板的格式,并保存好模板文件。在生成Word文档时,需要注意将数据插入到正确的位置,保持格式的一致性。通过这种方法,可以简化手动复制粘贴的过程,提高生成文档的效率,并确保数据的准确性。 ### 回答2: 将Excel中的数据按照Word模板生成Word文档可以通过使用VBA来实现。下面是具体的操作步骤: 1. 打开Excel文件并选择需要导入到Word中的数据。 2. 创建一个新的Word文档,并在文档中插入一个表格或者其他需要插入数据的位置。 3. 在Excel中,按下“ALT+F11”打开VBA编辑器。 4. 在VBA编辑器中,点击菜单栏中的“插入”,选择“模块”,添加一个新的模块。 5. 在新建的模块中编写VBA代码来实现将Excel数据导入到Word中的功能。可以使用Excel的对象模型来获取数据,使用Word的对象模型来进行文档的创建和修改。具体的代码可以查看相关的VBA编程教程和参考资料。 6. 完成VBA代码编写后,保存并关闭VBA编辑器。 7. 在Excel中选中需要导入的数据,运行刚刚编写的VBA。 8. VBA会自动将选中的数据按照Word模板生成Word文档,保存在指定的路径下。 需要注意的是,需要提前准备好Word模板,并确保模板中的表格或其他需要导入数据的位置与VBA中的代码一致。另外,VBA中还可以进行格式化和样式设置等操作,以满足生成Word文档的需求。 ### 回答3: 将Excel中的数据按照Word模板生成Word文档可以通过编写代码来实现。 首先,需要使用编程语言(比如Python)来进行开发。一个常用的工具是使用Python中的openpyxl库来读取Excel文件中的数据。可以逐行读取数据,并将其存储到相应的变量中。 接下来,需要使用Python中的python-docx库来操作Word文档。可以先打开Word模板文件,然后通过指定的关键字(比如占位符)来定位需要填充数据的位置。 然后,将从Excel中读取到的数据逐个填充Word模板中的相应位置。可以使用python-docx提供的功能,比如paragraphs和tables,来插入表格、段落或文字。 最后,保存生成Word文档文件。 这个过程中,可以添加一些附加的处理,比如格式化文本、插入图片等,以满足具体的需求。 总之,借助合适的编程语言和相关库的帮助,我们可以将Excel中的数据按照Word模板的格式生成Word文档
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值