Как решить проблему с извлечением таблицы Excel с арабским языком - PullRequest
0 голосов
/ 20 декабря 2018

Я экспортирую большую таблицу с большими данными в лист Excel / .csv с арабскими буквами.

При открытии листа возникает проблема, которую вы видите на изображении.

enter image description here

есть ли проблемы с моим кодом, или я должен использовать другой код?

public void DumpTableToFile(SqlConnection connection, string tableName, string destinationFile)
    {
        using (var command = new SqlCommand("select * from table " , connection))
        using (var reader = command.ExecuteReader())
        using (var outFile = File.CreateText(destinationFile))
        {
            string[] columnNames = GetColumnNames(reader).ToArray();
            int numFields = columnNames.Length;
            outFile.WriteLine(string.Join(",", columnNames));
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    string[] columnValues =
                        Enumerable.Range(0, numFields)
                                  .Select(i => reader.GetValue(i).ToString())
                                  .Select(field => string.Concat("\"", field.Replace("\"", "\"\""), "\""))
                                  .ToArray();
                    outFile.WriteLine(string.Join(",", columnValues));
                }
            }
        }
    }

    private IEnumerable<string> GetColumnNames(IDataReader reader)
    {
        foreach (DataRow row in reader.GetSchemaTable().Rows)
        {
            yield return (string)row["ColumnName"];
        }
    }

    private void Button5_Click(object sender, EventArgs e)
    {
        SqlConnection _connection = new SqlConnection();
        SqlDataAdapter _dataAdapter = new SqlDataAdapter();
        SqlCommand _command = new SqlCommand();
        DataTable _dataTable = new DataTable();

        _connection = new SqlConnection();
        _dataAdapter = new SqlDataAdapter();
        _command = new SqlCommand();
        _dataTable = new DataTable();

        //dbk is my database name that you can change it to your database name
        _connection.ConnectionString = "connaction";
        _connection.Open();

        SaveFileDialog saveFileDialogCSV = new SaveFileDialog();
        saveFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();

        saveFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
        saveFileDialogCSV.FilterIndex = 1;
        saveFileDialogCSV.RestoreDirectory = true;

        string path_csv = "";
        if (saveFileDialogCSV.ShowDialog() == DialogResult.OK)
        {
            // Runs the export operation if the given filenam is valid.
            path_csv = saveFileDialogCSV.FileName.ToString();
        }


        DumpTableToFile(_connection, "tbl_trmc", path_csv);

    }
}

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Используйте потоковую запись и укажите кодировку:

public void DumpTableToFile(SqlConnection connection, string tableName, string destinationFile)
{
    using (var command = new SqlCommand("select * from table " , connection))
    {
        using (var reader = command.ExecuteReader())
        {
            using (StreamWriter sw = new StreamWriter(File.Open(destinationFile, FileMode.Create), Encoding.Utf8))
            {    
                string[] columnNames = GetColumnNames(reader).ToArray();
                int numFields = columnNames.Length;
                sw.WriteLine(string.Join(",", columnNames)); // writing headers  

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string[] columnValues = Enumerable.Range(0, numFields)
                              .Select(i => reader.GetValue(i).ToString())
                              .Select(field => string.Concat("\"", field.Replace("\"", "\"\""), "\""))
                              .ToArray();
                        sw.WriteLine(string.Join(",", columnValues));
                    }
                }
            }
        }
    } 
}
0 голосов
/ 20 декабря 2018

Я думаю, вам нужно использовать кодировку, что-то вроде этого - для каждой информации -:

var utf8 = new UTF8Encoding();
...

string[] columnValues =
    Enumerable.Range(0, numFields)
        .Select(i => {
            if (reader[i].GetType() == typeof(SqlString))
            {
              SqlString sqlString = reader.GetSqlString(i);
              Byte[] encodedBytes = sqlString.GetNonUnicodeBytes();
              return "\"" + utf8.GetString(encodedBytes) + "\"";
            }
            else
            {
              return "\"" + reader[i].ToString() + "\"";
            }
         }).ToArray();
 ...

или

string[] columnValues =
    Enumerable.Range(0, numFields)
        .Select(i => reader[i].GetType() == typeof(SqlString) 
            ? utf8.GetString(reader.GetSqlString(i).GetNonUnicodeBytes()) 
            : reader[i].ToString())
        .Select(field => string.Concat("\"", field, "\""))
        .ToArray();

Для более подробной информации: msdn: utf8 varcharв байт []

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...