SSIS 脚本任务中的 C# 脚本将 "Text"格式的 Excel 列转换为 "General"

标签 c# excel visual-studio ssis number-formatting

我正在使用 SSIS 数据流任务将数据从 SQL Server 导出到 Excel。尽管导出格式,这里所有列都显示为文本。因此,我需要开发一个 SSIS 脚本任务来进行必要的转换。我在开发脚本时遇到了麻烦。

格式化前的 Excel 工作簿

Excel Workbook Before Formatting 看,Excel 单元格没有撇号,数字类型也是“常规”,但消息显示此单元格中的数字格式为文本或前面有撇号/p>

我尝试了互联网上可用的不同选项,但没有成功。

#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
#endregion

namespace ST_de899f405b7b4083b0ad8cba6b3df2e3
{

[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
    public void Main()
    {
        string inputFile = (string)Dts.Variables["Target_FullFilePath"].Value;
        Excel.Application ExcelApp = new Excel.Application();
        Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(inputFile);
        Excel.Range formatRange;
        ExcelApp.Visible = true;

        foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
        {
            ExcelWorksheet.Select(Type.Missing);
            ExcelWorksheet.Columns[2].NumberFormat = "";
            ExcelWorksheet.Columns[3].NumberFormat = "";
            ExcelWorksheet.Columns[4].NumberFormat = "0.00000";
            ExcelWorksheet.Columns[5].NumberFormat = "yyyy-MM-dd";
        }

        ExcelWorkbook.Save();

        GC.Collect();
        GC.WaitForPendingFinalizers();

        ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
        Marshal.FinalReleaseComObject(ExcelWorkbook);

        ExcelApp.Quit();
        Marshal.FinalReleaseComObject(ExcelApp);
    }   
    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
    #endregion
}
}

预期结果:编号为 B、C、D 的列看起来像小数/整数,并且也进行了类似的过滤。 E看起来像 Date 并且也进行了类似的过滤。

这就是我希望 Excel 文件在通过 SSIS 格式化后的样子

What I want through Script in SSIS

我确认相应的列只有列标题除外的相关值。

最佳答案

在提供解决方案之前,我必须解释一下有关 Excel 数字格式的一些要点

什么是数字格式属性?

引用Number format codes文档:

You can use number formats to change the appearance of numbers, including dates and times, without changing the actual number. The number format does not affect the cell value that Excel uses to perform calculations. The actual value is displayed in the formula bar.

什么是通用编号格式?

引用Reset a number to the General format文档:

The General format is the default number format that Excel applies when you type a number. For the most part, numbers that are formatted with the General format are displayed just the way that you type them.

日期在Excel中是如何存储的?

引用How Dates Work in Excel :

The dates in Excel are actually stored as numbers, and then formatted to display the date.

你的异常(exception)结果

你提到过:

Expected Result: Columns numbered 16, 17, 22 to be converted to "General" and look like decimal numbers. Column 31 to be converted to "General" and look like Date.

根据我们提到的内容,您不能将第 31 列转换为“常规”并使其看起来像日期。

解决方案

您只需将 NumberFormat 属性设置为空字符串即可将其设置为“常规”

ExcelWorksheet.Columns[16].NumberFormat = "";

实验

我创建了一个包含 4 列的 Excel 文件:NumberColumn、DateColumn、DecimalColumn 和 StringColumn,如上图所示:

enter image description here

我使用以下代码创建了一个控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputFile = @"D:\Test.xlsx";

            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(inputFile);
            ExcelApp.Visible = true;

            foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
            {
                ExcelWorksheet.Select(Type.Missing);

                ExcelWorksheet.Columns[1].NumberFormat = "";
                ExcelWorksheet.Columns[2].NumberFormat = "yyyy-MM-dd"; // convert format to date
                ExcelWorksheet.Columns[2].NumberFormat = "";
                ExcelWorksheet.Columns[3].NumberFormat = "0.00000"; // convert format to decimal with 5 decimal digits
                ExcelWorksheet.Columns[3].NumberFormat = "";
                ExcelWorksheet.Columns[4].NumberFormat = "";


            }
            ExcelWorkbook.Save();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(ExcelWorkbook);

            ExcelApp.Quit();
            Marshal.FinalReleaseComObject(ExcelApp);
        }
    }
}

执行应用程序后,Excel 如下所示:

enter image description here

讨论与结论

从上图中,我们可以看到所有列都更改为通用数字格式,但如果值存储为数字,它们将按存储方式显示:日期值显示为 Excel 序列(数字)、十进制值即使我们在将格式重置为“常规”之前将格式更改为五位数,也仅显示一位小数。

简而言之,当数字格式为“常规”时,您无法处理值的显示方式,如果您需要将值显示为日期,则必须将数字格式设置为 yyyy-MM-dd 或任何其他日期格式。

引用


更新1

不要使用 ExcelWorksheet.Columns[1].NumberFormat,请尝试使用以下代码:

ExcelWorksheet.Cells[1,1].EntireColumn.NumberFormat = "";
ExcelWorksheet.Cells[1,2].EntireColumn.NumberFormat = "";

关于SSIS 脚本任务中的 C# 脚本将 "Text"格式的 Excel 列转换为 "General",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57460180/

相关文章:

vba - 关闭录制的 VBA 宏的 R1C1 引用样式

excel - 无法获取 WorksheetFunction 类的 Vlookup 属性

excel - 如何对从两列相乘返回的所有值求和?

c++ - Visual-Studio 教程,介绍如何将所有代码放在一个目录中,并将所有 sln 和 proj 内容放在另一个目录中?

asp.net - 经典 ASP Intranet 和新的 ASP.NET 应用程序

visual-studio - 是否有键盘快捷键可以查看 Visual Studio 中波浪线的含义?

C# 转换问题 : from IEnumerable to custom type

MultiSelectList 中的 C# .NET 查询不起作用

c# - 设计师强制将资源嵌入到表单中,而不是使用 Resources.resx?

c# - 锁定(文件)以在页面之间写入?