首页 > 解决方案 > 将 DataTable 导出到 Excel 文件显示?关于数学符号

问题描述

我正在开发一个 WPF 应用程序,我需要将我的数据导出到 excel 中。我有分数、度数、幂符号等的数学查询数据。我能够正确查看我的数据,但是当我将数据导出到 excel 时,它会将这些符号更改为 ?

以前我使用Encoding.ASCII作为数据然后我知道我们需要改变它的东西。我尝试过UTF7、UTF8、Unicode 和 Default,但没有任何效果。尽管我能够使用Encoding.Default正确获取一些数据, 但在搜索时,我了解了Office Interlop,但要正确运行它,您需要安装 MS Office excel,我不想对我的项目产生这种依赖性。

  int rowIndex = 1;
        colIndex = 0;
  foreach (DataRow row in dvRecords.Table.Rows)
        {
            foreach (DataColumn col in dvRecords.Table.Columns)
            {
                if (row[col] != null)
                {

                    if (col.DataType == typeof(int))
                        this.WriteCell(rowIndex, colIndex, Convert.ToInt32(row[col]));
                    else if (col.DataType == typeof(double))
                        this.WriteCell(rowIndex, colIndex, Convert.ToDouble(row[col]));
                    else if (col.DataType == typeof(bool))
                        this.WriteCell(rowIndex, colIndex, (Convert.ToBoolean(row[col]) ? "Yes" : "No"));
                    else
                        this.WriteCell(rowIndex, colIndex, Convert.ToString(row[col]));

                    colIndex++;
                }
            }
            rowIndex++;
            colIndex = 0;
        }

写入单元方法

 private BinaryWriter _writer;

 private void WriteCell(int row, int col, string value)
    {

        ushort[] clData = { 0x0204, 0, 0, 0, 0, 0 };
        byte[] plainText = Encoding.Default.GetBytes(value);
        int iLen = plainText.Length;
        clData[1] = (ushort)(8 + iLen);
        clData[2] = (ushort)row;
        clData[3] = (ushort)col;
        clData[5] = (ushort)iLen;
        WriteUshortArray(clData);
        _writer.Write(plainText);
    }

 private void WriteUshortArray(ushort[] value)
    {
        for (int i = 0; i < value.Length; i++)
            _writer.Write(value[i]);
    }

我希望从我的 DataTable 数据中将符号正确导入到 excel 中,但我得到的数据是“?” 象征

标签: c#.netwpfdatatableexport-to-excel

解决方案


尝试使用这个:

plainText = "<html><head><meta charset=""" & Encoding.UTF8.WebName & """ /></head><body>" & plainText & "</body></html>";
_writer.Write(plainText);
_writer.End();

Excel无法读取UTF-8编码默认值,但它使用html <div>-s 和table标签生成 excel 表


推荐阅读