【问题标题】:Save CSV with UTF-8 encoding on export using SQL Server Management Studio 2005使用 SQL Server Management Studio 2005 在导出时使用 UTF-8 编码保存 CSV
【发布时间】:2014-06-21 11:29:48
【问题描述】:

我正在尝试使用 SQL Server Management Studio 2005 导出 CSV 文件,并尝试单击保存旁边的下拉按钮并选择编码 UTF,但它仍保存为 UCS-2 小端编码。

是否可以使用 UTF-8 编码而不用 Notepad++ 打开并保存为 UTF-8?额外的步骤等等。

【问题讨论】:

    标签: sql-server csv utf-8 ucs2


    【解决方案1】:

    由于 MS SQL Server 仅输出为 UCS-2 Little Endian 或 ASII 编码,您可以使用 bcp 调用一个小 C# 程序将其转换为 UTF-8

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace UCS2toUTF8
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (args.Length != 1)
                {
                    Console.WriteLine("exampe: UCS2toUTF8 [filepath]");
                    return;
                }
    
                var filename = args[0];
    
                var filestream = File.OpenRead(filename);
    
                var BOM = new byte[3];
    
                filestream.Read(BOM, 0, BOM.Length);
    
                if (BOM[0] != (byte)255 && BOM[1] != (byte)254 ) //0xff 0xfe 0x48
                {
                    Console.WriteLine("This isn't UCS-2LE");
                    return;
                }else if (BOM[0] == 0xEF && BOM[1] == 0xBB && BOM[2] == 0xBF)
                {
                    Console.WriteLine("This is UTF-8");
                    return;
                }
    
                filestream.Close();
    
                byte[] content = File.ReadAllBytes(filename);
    
                byte[] utf8Bytes = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.UTF8, content);
    
                byte[] newArray = new byte[utf8Bytes.Length - 3];
    
                Array.Copy(utf8Bytes, 3, newArray, 0, newArray.Length);
    
                File.WriteAllBytes(filename, newArray);
            }
        }
    }
    

    请注意,如果你想要 UTF-8 和 BOM,你需要做一些修改。

    【讨论】:

      【解决方案2】:

      因为我需要一个应用程序来为我执行此操作,所以我使用 vb 来执行此操作,使用以下链接帮助 http://www.vbnettutorial.net/?Id=119&Desc=Export-CSV-from-Dataset How to export a csv file based on a SQL query programatically

      【讨论】:

        猜你喜欢
        • 2014-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 2010-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多