c# - 如何使用 iTextSharp 将 C# DataGridView 导出为 PDF,同时**维护自定义货币格式**?

标签 c# winforms itext

我正在尝试使用 iTextSharp 将具有自定义货币格式的 DataGridView 导出为 PDF,运行程序时该格式完美显示在 DataGrid 上,但保存后就不会出现在 PDF 上。

这是 DataGridView 代码(显示货币格式):

    DataTable t = new DataTable();

            if (t != null)
            {
                a.Fill(t);

                //Custom currency formatting
                var format =              (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
                format.CurrencySymbol = "R";

                dgvMiscEntries.AutoGenerateColumns = false;

                dgvMiscEntries.ColumnCount = 2;
                 //Assign column headers manually

                dgvMiscEntries.Columns[0].Name = "Description";
                dgvMiscEntries.Columns[0].HeaderText = "Description";
                dgvMiscEntries.Columns[0].DataPropertyName = "Description";

                dgvMiscEntries.Columns[1].Name = "Rate";
                dgvMiscEntries.Columns[1].HeaderText = "Rate";
                dgvMiscEntries.Columns[1].DataPropertyName = "Rate";
                dgvMiscEntries.Columns[1].DefaultCellStyle.FormatProvider =     format;
                dgvMiscEntries.Columns[1].DefaultCellStyle.Format = "c";


                // Render data onto grid
                dgvMiscEntries.DataSource = t;
            }

这是 iTextSharp 代码:

            //Creating iTextSharp Misc Entries Table from the DataTable data
            PdfPTable miscTable = new PdfPTable(dgvMiscEntries.ColumnCount);
            miscTable.DefaultCell.Padding = 3;
            float[] miscWidthPosit = new float[] { 1000f, 200f };
            miscTable.WidthPercentage = 80;
            miscTable.SetWidths(miscWidthPosit);
            miscTable.HorizontalAlignment = Element.ALIGN_CENTER;
            miscTable.DefaultCell.BorderWidth = 1;
            miscTable.SpacingBefore = 10;
            miscTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

            foreach (DataGridViewRow row in dgvMiscEntries.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value != null)
                    {
                        miscTable.AddCell(cell.Value.ToString());
                    }
                }
            }

我在这里和其他网站上搜索了类似的问题,但没有找到任何解决此特定问题的方法。

最佳答案

这是因为 Value 属性采用实际的绑定(bind)值,该值用于提供格式化文本。

所以而不是

miscTable.AddCell(cell.Value.ToString());

使用FormattedValue

miscTable.AddCell(cell.FormattedValue.ToString());

关于c# - 如何使用 iTextSharp 将 C# DataGridView 导出为 PDF,同时**维护自定义货币格式**?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588653/

相关文章:

wpf - Windows 窗体是旧技术吗?

c# - C# 窗体切换时的闪烁效果

c# - 将 Windows 窗体单元测试迁移到 WPF

c# - 如何使用 itextsharp 更改 PDF 公式的按钮图标?

c# - 底部的 PDF 页脚使用 iTextSharp

c# - ELMAH - 它是否记录引用 URL

c# - WPF TreeView - 选择和扩展节点

c# - 为自动化存储密码的最佳实践

c# - 附加到其他 PDF 文件后无法删除 PDF 文件 - C# - ItextSharp

c# - 使用 UI 自动化选择组合框项目