- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个 word 模板文件,其中包含一个表格,它有 11 行和 3 列。所以第一页的表格中有 33 个单元格。我用一些数据填充这些单元格,但是如果记录数大于 33(比如 66),我将创建两个文件,每个文件包含 33 条记录。我想创建一个包含所有 66 条记录的文件,一个文件中应该有两页,而不是两个单独的文件。我应该怎么做?
以下是我用来创建一个文档文件的代码。
private static string FillTemplate(List<ClientListItem> clients, string fileName)
{
//Filled document file name
var savedFileName = string.Empty;
//Search template file in current directory
var templateFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "templateFile.doc";
#region Generate file for labels
object missing = System.Type.Missing;
// Create Word application
WORD._Application app = new WORD.Application();
try
{
Print("Creating label document.");
// Create new file
WORD._Document doc = app.Documents.Open(templateFilePath);
//Print("Creating app selection object");
WORD.Selection selection = app.Selection;
//If the template file contains tables
if (selection.Tables.Count > 0)
{
//Use first table
//Table's are accessed with starting index as 1 not 0
var tableToUse = selection.Tables[1];
//Counter for number of parent caregivers inserted
var counter = 0;
//Number of parent caregivers
var numberOfParentCaregivers = clients.Count;
//Loop on each row
//Rows are accessed with starting index as 1 not 0
for (int rowIndex = 1; rowIndex <= tableToUse.Rows.Count; rowIndex++)
{
//Loop on each column
//Columns are accessed with starting index as 1 not 0
for (int columnIndex = 1; columnIndex <= tableToUse.Columns.Count; columnIndex++)
{
//If counter has reached to its limit
if (counter + 1 > numberOfParentCaregivers)
{
//Stop
break;
}
//If current column index is even
if (columnIndex % 2 == 0)
{
//Do not process it
//Why? Check template file for yourself
continue;
}
//Get parent caregiver to set
var parentCaregiver = clients[counter];
Print("Generating label to add to document.");
//Get label to add to document
var labelToAdd = string.Format("{0} {1},{6}{2},{6} {3}, {4} {5}", parentCaregiver.Parent1LastName, parentCaregiver.Parent1FirstName,
parentCaregiver.Parent1StreetAddress, parentCaregiver.Parent1City, parentCaregiver.Parent1State, parentCaregiver.Parent1Zip, Environment.NewLine);
//Print(string.Format("Adding label {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex));
//Get cell to set value
var tableCell = tableToUse.Cell(rowIndex, columnIndex);
//Set text in cell
tableCell.Range.Text = labelToAdd;
//Middle align text
tableCell.Range.ParagraphFormat.Alignment = WORD.WdParagraphAlignment.wdAlignParagraphCenter;
Print(string.Format("Label added {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex));
counter++;
}
//If counter has reched to its limit
//i.e. no parent caregivers to process - all processed
if (counter + 1 > numberOfParentCaregivers)
{
//stop
break;
}
}
}
// Set file name to save
savedFileName = string.Format(@"{0}{1}{2}", Path.GetTempPath(), fileName, Path.GetExtension(templateFilePath));
object fname = savedFileName;
Print(string.Format("Saving new document at {0}", savedFileName));
// SaveAs new file
doc.SaveAs(ref fname, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
Print(string.Format("{0} saved successfully.", savedFileName));
app.Documents.Close(ref missing, ref missing, ref missing);
}
catch (Exception exc)
{
Print("Exception while generating label document");
Print(exc.ToString());
//Set file Name to empty string
savedFileName = string.Empty;
}
finally
{
// Close Word application
app.Quit(ref missing, ref missing, ref missing);
Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
//Return saved file name
return savedFileName;
}
请提出更改建议,以便我可以根据要添加到模板文件中的记录数创建任意数量的页面。
谢谢,尼克尔。
最佳答案
我更改了您的代码,循环遍历要插入表格中的所有项目,而不是循环遍历表格的单元格。在此循环内,列和行的索引递增,当所有单元格都已填充时,将在粘贴原始表格副本的文档末尾插入分页符。此时两个索引都重置为1,新表被设置为要使用的表,一切正常继续。
这是代码:
private static string FillTemplate(List<ClientListItem> clients, string fileName)
{
//Filled document file name
var savedFileName = string.Empty;
//Search template file in current directory
var templateFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "templateFile.doc";
object missing = System.Type.Missing;
// Create Word application
WORD._Application app = new WORD.Application();
try
{
app.Visible = true;
Print("Creating label document.");
// Create new file
WORD._Document doc = app.Documents.Open(templateFilePath);
//Print("Creating app selection object");
WORD.Selection selection = app.Selection;
//If the template file contains tables
if (selection.Tables.Count > 0)
{
//Use first table
var tableToUse = selection.Tables[1];
//copy the empty table in the clipboard
WORD.Range range = tableToUse.Range;
range.Copy();
int rowIndex = 1;
int columnIndex = 1;
// loop over all the items to insert
foreach (ClientListItem parentCaregiver in clients)
{
// check if all the cells in the current row have been used
if (columnIndex > tableToUse.Columns.Count)
{
// if this is the case increment the row index and restart from the first column
columnIndex = 1;
rowIndex++;
// check if all the rows in the current table have been used
if (rowIndex > tableToUse.Columns.Count)
{
// if this is the case create a new table and restart from the first row
rowIndex = 1;
// first go to end of document
selection.EndKey(WORD.WdUnits.wdStory, WORD.WdMovementType.wdMove);
// then add page break
object breakType = WORD.WdBreakType.wdPageBreak;
selection.InsertBreak(ref breakType);
// add a new table (initially with 1 row and one column) at the end of the document
// i.e. on the new page
WORD.Table tableCopy = doc.Tables.Add(selection.Range, 1, 1, ref missing, ref missing);
// paste the original empty table over the new one
tableCopy.Range.Paste();
// makes the copied table the one to use
tableToUse = tableCopy;
}
}
Print("Generating label to add to document.");
//Get label to add to document
var labelToAdd = string.Format("{0} {1},{6}{2},{6} {3}, {4} {5}", parentCaregiver.Parent1LastName, parentCaregiver.Parent1FirstName,
parentCaregiver.Parent1StreetAddress, parentCaregiver.Parent1City, parentCaregiver.Parent1State, parentCaregiver.Parent1Zip, Environment.NewLine);
//Get cell to set value
var tableCell = tableToUse.Cell(rowIndex, columnIndex);
//Set text in cell
tableCell.Range.Text = labelToAdd;
//Middle align text
tableCell.Range.ParagraphFormat.Alignment = WORD.WdParagraphAlignment.wdAlignParagraphCenter;
Print(string.Format("Label added {0} at {1}, {2} position.", labelToAdd, rowIndex, columnIndex));
columnIndex++;
}
}
// Set file name to save
savedFileName = fileName; // string.Format(@"{0}{1}{2}", Path.GetTempPath(), fileName, Path.GetExtension(templateFilePath));
object fname = savedFileName;
Print(string.Format("Saving new document at {0}", savedFileName));
// SaveAs new file
doc.SaveAs(ref fname, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
Print(string.Format("{0} saved successfully.", savedFileName));
app.Documents.Close(ref missing, ref missing, ref missing);
}
catch (Exception exc)
{
Print("Exception while generating label document");
Print(exc.ToString());
//Set file Name to empty string
savedFileName = string.Empty;
}
finally
{
// Close Word application
app.Quit(ref missing, ref missing, ref missing);
Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
//Return saved file name
return savedFileName;
}
关于c# - Word 互操作 C# : Insert new page using existing page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40677666/
我试图找出如何访问 ClojureScript 中的 Javascript 对象属性。如果我事先知道属性(property)的名称,那就很容易了。获取foo.bar我只是做 (.-bar foo) I
我是 .NET 的新手。我想制作一个控制台应用程序,将 .pptx 文件转换为 .wmv。我已经使用 powerpoint interop 做到了这一点。但我有一些问题。首先,如果我构建应用程序并将其
我计划将我的许可系统的核心转移到 C++,但我仍然更喜欢使用 .NET 前端进行设计。无论如何,我刚刚读完互操作功能,并决定对其进行测试。问题是,它对我来说只是花花公子,但对任何其他用户都不起作用。我
系统管理员正在编写一些常用的管理 Power Shell 脚本。主要用于 AD 管理(更新交易所详细信息、在安全组中移动人员等) 我想使用 C# 中的这些脚本(我打算将其编写为库,供网站使用)。 我看
我想在我的应用程序中使用 COM 对象。 如何确保对象已在机器中注册? 我找到的唯一解决方案(也是 on SO)是在初始化周围使用 try-catch block : try { Foo.Ba
这个问题在这里已经有了答案: How to call Java code from C#? (4 个答案) 关闭 10 个月前。 您能给我一些关于使 C# 代码和 Java 代码互操作的建议吗?让我
我正在使用 Microsoft.Office.Interop.Excel 从 C# 创建一个 Excel 工作表,但我无法按照用户想要的方式获取页脚。 1) 如何将页脚文本加粗? 2)如何将页码放在页
我正在使用 F# 和 Excel Interop 将数据输出到 Excel 电子表格。我的第一种方法是单独设置每个单元格: worksheet.Range(range1).Value2 <- "=su
与来自 Silverlight 的 COM 控件进行交互的选项有哪些? 在我的特定项目中,我有一个旧的 ActiveX 身份验证控件,我想在我的 Silverlight 应用程序中利用它。没有太多无聊
我需要针对以下场景的一些建议: 我的 Uni 组有一个巨大的 SVN 存储库。我实际上对整个项目的子目录感兴趣(例如/trunk/projects/my_project)- 不知道它是否真的与 SVN
我有一个 .NET 程序集,它是通过 COM Interop 从 Delphi 主机调用的。据我所知,.NET 代码中任何未处理的异常都将由 .net com 互操作框架处理,并且相应的 HRESUL
我有一个程序可以在单击按钮时创建两个 pdf 文件。它在 WinForms 中使用 Microsoft Office 互操作,文件创建过程如下; 用户在程序中工作 点击按钮 程序根据一个带有书签的模板
我有一个第三方 DLL 用 Delphi“a.dll”(无源代码)编写。 这个 DLL 有一个带有这个签名的方法。 function GetAny(pFileName: String): String
想知道是否有人成功使用 JDEdwards XMLInterop 功能。我已经使用它有一段时间了(使用一个简单的 PInvoke,稍后将发布代码)。我正在寻找是否有更好和/或更强大的方法。 谢谢。 最
我正在尝试让 javafx2 与 Clojure 一起使用 - 在实现像 DoubleBinding 这样的抽象类时,我不确定 Clojure 中 super.bind(moo) 的等价物是什么。我正
有人有使用 Firebird 与 .NET 框架互操作的经验吗?如果有,进展如何? 最佳答案 我在商业桌面应用程序中使用了 firebird。 它的性能很好,直到您处理返回大型结果集的查询。在这些情况
我正在 Excel 工作表中复制并插入行,如下所示: while (rowsToAdd > 0) { // copy the existing row insert
我无法确保正确销毁托管窗口。 我有一个 HwndHost 派生类,正在 TabControl 中显示(尽管这可能不相关)。我试图在选项卡关闭时销毁托管内容(而不是在包含的窗口关闭时)。 我目前拥有 m
我有两个 python 类,它们都可以使用 COM 互操作机制独立于 VBA 编写脚本。但我希望一个能够以父子模式或工厂模式控制另一个的创建。 我已经尝试过,但无法开始工作,我已将其提炼为下面的 MC
我们在我们编写的 C# dll(程序集 A)中使用 Microsoft 提供的 COM DLL (dsofile.dll)。为了避免必须注册 COM dll,我已将对 dsofile.dll 的引用的
我是一名优秀的程序员,十分优秀!