生成的Word文档中如何格式化单元格

3
我正在我的LightSwitch账单应用程序中生成发票,在生成发票之后,Word文档中的SubTotal、SalesTax和Total Due单元格格式不正确。
我已经查看了每个菜单选项,并探索了其他可能的方式,在它被放入文档内容控件之前进行格式化,但我无法得到正确的格式。
这些数字显示为“4100.0000”,但它们应该像“4,100.00”或至少像“4100.00”。
如何做到这一点?
我意识到这与主题边界有关,但我认为解决方案涉及编写代码,而不是使用Word来完成这个问题,因为我已经查看了所有选项,似乎没有一个选项可以更改单个单元格的格式。
所请求的文档生成代码:
using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using OfficeIntegration;
namespace LightSwitchApplication
{
    public partial class Billing
    {
        partial void GenerateInvoice_Execute()
        {
            var mappings = new List<ColumnMapping>();

            mappings.Add(new ColumnMapping("InvoiceId", "InvoiceId"));
            mappings.Add(new ColumnMapping("DateGenerated", "DateGenerated"));

            mappings.Add(new ColumnMapping("InvoiceDataGridSubTotal", "SubTotal"));
            mappings.Add(new ColumnMapping("InvoiceDataGridSalesTax", "Tax"));
            mappings.Add(new ColumnMapping("InvoiceDataGridDateDue", "DateDue"));
            mappings.Add(new ColumnMapping("InvoiceDataGridTotalDue", "Total"));

            object doc;
            string path = @"C:\Users\Jason\Documents\SV Invoice.docx";

            doc = OfficeIntegration.Word.GenerateDocument(path, this.BillingTables.SelectedItem, mappings);
        }
    }
}

1
请展示一下如何将数字写入这些单元格。 - Daniel Hilgarth
该应用程序会自动填充Word文档中的单元格。但是,当我将数字输入到我的lightswitch应用程序时,我总是将它们输入为“4,100.00”。而且,即使我没有这样做,Lightswitch应用程序也会自动格式化它们——因此,我认为它们应该以正确的格式显示在Word文档中。 - Arrow
1
“Auto-populate” 是什么意思?请展示代码。 - Daniel Hilgarth
@DanielHilgarth:添加了完整的代码。 - Arrow
2个回答

2
在这种情况下,不需要进行代码和单词格式设置。为了使动态生成的Word文档中的数字正确格式化,您必须从Visual Studio LightSwitch的Data Designer中设置要使用的格式:
  • 打开LightSwitch项目
  • 展开项目节点>打开包含要格式化的数字的表格
  • 选择需要格式化的字段
  • 属性窗格中,向下滚动直到看到Formatting (Format Pattern)
  • 现在在这里格式化数字。请参见链接以获取可用选项。我选择使用C2格式。
通过上述步骤,我能够为货币生成以下格式的Word文档: 4500.00而不是4500.0000

1

您应该能够向ColumnMapping构造函数提供第三个参数:一个格式化值的委托:

Func<decimal, string> formatDelegate = x => x.ToString("c2");
mappings.Add(new ColumnMapping("InvoiceDataGridSubTotal", "SubTotal",
                               FormatDelegate: formatDelegate));

当前上下文中不存在名称为'Format'的内容。关于更新。 - Arrow
@Iateyourtoothpaste:新版本怎么样了? - Daniel Hilgarth
抱歉,它不会产生错误,但它不再显示数字。它只是将以下文本输出到Word文档中:System.Func`2[System.Decimal,System.String]。 - Arrow
非常感谢您的帮助。它让我走上了正确的道路,找出了如何格式化它们的方法 - 我还学会了如何使用委托,哈哈 - 我已经成功解决了这个问题;我刚刚写了一个答案。关于ColumnMapping构造函数的参数:ColumnMapping.ColumnMapping(string OfficeColumnName, List<FieldDefinition> TableFields)ColumnMapping.ColumnMapping(string OfficeColumnName, string EntityFieldName, [objectStaticValue = null], [Delegate FormatDelegate = null]) - Arrow
1
@Iateyourtoothpaste:感谢提供构造函数的参数。我的最新版本应该可以工作了。但是你的方法适用于简单的格式化。 - Daniel Hilgarth
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接