public void MakeUpPostCode(System.Collections.Generic.List<vAllCommonUser> data, string targetFullFileName)
{
Object Nothing = System.Reflection.Missing.Value;
try
{
//取得Word文件保存路径
object filename = targetFullFileName;
//创建一个名为WordApp的组件对象
//Microsoft.Office.Interop.Word.Application WordApp = new ApplicationClass();
//网络上有写代码中直接使用Word.Application WordApp = new ApplicationClass(); 但我在实际编写中总是出现错误。
//创建一个名为WordDoc的文档对象
WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordDoc.Activate();
WordDoc.PageSetup.LeftMargin = 18;
WordDoc.PageSetup.RightMargin = 18;
WordDoc.PageSetup.TopMargin = 18;
WordDoc.PageSetup.BottomMargin = 18;
//增加一表格
var rows = Convert.ToInt16(Math.Ceiling(Convert.ToDouble(data.Count) / 2));
Microsoft.Office.Interop.Word.Table table = WordDoc.Tables.Add(WordApp.Selection.Range, rows, 2, ref Nothing, ref Nothing);
table.Rows.HeightRule = WdRowHeightRule.wdRowHeightExactly;
table.Rows.Height = 134;
//在表格第一单元格中添加自定义的文字内容
table.Columns[1].Width = 279;
table.Columns[2].Width = 279;
for (var i = 0; i < data.Count; i++)
{
EntryModel model = new EntryModel();
var city = "";
var county = "";
if (data[i].COMP_Addr_City != null && data[i].COMP_Addr_City.Value != AppConst.DefaultGuid)
{
city = model.getItem(data[i].COMP_Addr_City.Value).Name;
county = model.getItem(data[i].COMP_Addr_County.Value).Name;
}
var row = i == 0 ? 1 : (i % 2 == 1 ? (i + 1) / 2 : (i / 2) + 1);
table.Cell(row, (i % 2) + 1).Range.Text = "" +
data[i].ContactZip + "\n" +
city+county+ data[i].COMP_Addr + "\n" +
data[i].Company + " " + data[i].MemberID + "\n" +
(data[i].MemberKind == 3 ? data[i].RealName : data[i].VIP1) + " " + data[i].VIP1Title + " 鈞啓\n" +
"聯絡人:" + data[i].Contact + " (內含會費到期通知)\n";
table.Cell(row, (i % 2) + 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
}
//table.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth025pt;
//在文档空白地方添加文字内容
// WordDoc.Paragraphs.Last.Range.Text = "Wellcome To Aspxcn.Com";
//将WordDoc文档对象的内容保存为DOC文档
WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
try
{
//关闭WordDoc文档对象
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭WordApp组件对象
WordApp.Application.Quit(ref Nothing, ref Nothing, ref Nothing);
}
catch (Exception e2)
{
}
}
这是以前写的一个创建word并添加表格的方法,你看看吧
谢谢提供的代码!
表格的行和列索引都是从1开始的吧
这个是正解,注意索引开始不是0
创建word表格可以试试这个https://www.e-iceblue.cn/docjava/create-table-in-word-in-java.html