返回文件(内存流)编码

时间:2016-01-17 19:08:24

标签: c# asp.net-mvc

嗨我有问题返回正确的编码文件。

finalString仅限于我控制编码并向我显示正确的字符串,但返回的excel文件不包含正确的捷克字符...(Č蚊Ž等...)有人可以帮助我吗?

 byte[] bytes = encode.GetBytes(str.ToString());
 string finalString = encode.GetString(bytes);

这是完整的课程:

public async Task<IActionResult> ExportExcel()
    {
       // List<Material> obj = new List<Material>();
       // obj = await _context.Material.ToListAsync();

        StringBuilder str = new StringBuilder();
        str.Append("<table border=`" + "1px" + "`b>");
        str.Append("<tr>");
        str.Append("<td><b>Id</b></td>");
        str.Append("<td><b>Name</b></td>");
        str.Append("</tr>");

      //  foreach (Material val in obj)
       // {
            str.Append("<tr>");
            str.Append("<td>" + "0" + "</td>");
            str.Append("<td>" + Česnek + "</td>");
            str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Name.ToString() + "</font></td>");
            str.Append("</tr>");
       // }

        str.Append("</table>");


        string uc = Configuration.UserCulture;
        int codepage =  1250; // _cultureDataProvider.GetAnsiCodePage(uc);
        Encoding encode = Encoding.GetEncoding(codepage);

        byte[] bytes = encode.GetBytes(str.ToString());
        string finalString = encode.GetString(bytes);
        MemoryStream stream = new MemoryStream(bytes);

        return File(stream, "application/vnd.ms-excel", "excel.xls");


        /*
        HttpContext.Response.Headers.Add("content-disposition", "attachment; filename=Information" + DateTime.Now.Year.ToString() + ".xls");
        this.Response.ContentType = "application/vnd.ms-excel";
        byte[] temp = System.Text.Encoding.ASCII.GetBytes(str.ToString());
        return File(temp, "application/vnd.ms-excel");
        */
    }

2 个答案:

答案 0 :(得分:1)

ANSI不为Č, č, š, Š, Ž提供有效的编码,您应该寻找更合适的代码页,如UTF-8,UTF-16,UTF-32等....

byte[] bytes = Encoding.UTF8.GetBytes(str.ToString());
string finalString = Encoding.UTF8.GetString(bytes);

您是否尝试使用Office Interop?使用Excel将更加轻松和正确。

这是简单的工作表管理器

public class ExcelManager
{
    public ExcelManager()
    {
        ItsApplication = null;
        ItsWorkbook = null;
        ItsWorksheet = null;


        AppInitialization = false;
        WrbInitialization = false;
        WrsInitialization = false;
    }
    /*////////////////////////////////////////////////////*/
    public void Initialize(bool visible)
    {
        try
        {
            if (ItsApplication == null)
            {
                ItsApplication = new Microsoft.Office.Interop.Excel.Application();
                ItsApplication.SheetsInNewWorkbook = 1;
                ItsApplication.Visible = visible;
                AppInitialization = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
    public void CreateWorkbook()
    {
        try
        {
            if (ApplicationInitialized)
            {
                ItsWorkbook = ItsApplication.Workbooks.Add(MissingValue);
                WrbInitialization = true;
            }
            else
                MessageBox.Show(
                    "Couldnot create workbook!\n" +
                    "App instance didnot initialized!",
                    "Error!!!", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
    public void CreateWorksheet()
    {
        try
        {
            if (WorkbookInitialized)
            {
                ItsWorksheet = ItsWorkbook.Worksheets.Add(MissingValue,
                    MissingValue, MissingValue, MissingValue);

                WrsInitialization = true;
                CurrentRow = 1;
            }
            else
                MessageBox.Show(
                    "Couldnot create worksheet!\n" +
                    "Workbook didnot created!", 
                    "Error!!!", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
    public void SetText(string text,int bold,int italic,int cells_offset)
    {
        try
        {
            if (WorksheetInitialized)
            {
                ArrayList lines_list = new ArrayList();
                string curr_line = "";

                for (int i = 0; i < text.Length; i++)
                {
                    if (text[i] == '\n' || (i == text.Length - 1))
                    {
                        lines_list.Add(curr_line);
                        curr_line = "";
                    }
                    curr_line += text[i];
                }

                CurrentRow += cells_offset;

                foreach (object line in lines_list)
                {
                    Range text_range =
                        ItsWorksheet.get_Range("A" + CurrentRow, "A" + CurrentRow);

                    text_range.Font.Bold = bold;
                    text_range.Font.Italic = italic;
                    text_range.Value2 = line;
                    text_range.WrapText = false;

                    CurrentRow++;
                }
            }
            else
                MessageBox.Show(
                    MessageBox.Show(
                    "Cannot output any text!\n" +
                    "Worksheed didnot created!",
                    "Error!!!", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }

    public void SetData(System.Data.DataTable table, int bold, int italic,int rows_offset)
    {
        try
        {
            if (WorksheetInitialized)
            {
                CurrentRow += rows_offset;

                int TableRows = table.Rows.Count;
                int TableCols = table.Columns.Count;

                char ACol = 'A';

                Range TableRange = ItsWorksheet.get_Range("A" + CurrentRow,
                    ((char)((int)ACol + TableCols - 1)).ToString() + (CurrentRow + TableRows).ToString());

                TableRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;


                for (int i = 0; i < TableCols; i++)
                {
                    Range names_range = ItsWorksheet.get_Range(((char)((int)ACol + i)).ToString() + CurrentRow,
                        ((char)((int)ACol + i)).ToString() + CurrentRow);
                    names_range.Value2 = table.Columns[i].ColumnName;
                }

                for (int i = 1; i < TableRows + 1; i++)
                {
                    for (int j = 0; j < TableCols; j++)
                    {
                        Range cell_range = ItsWorksheet.get_Range(((char)((int)ACol + j)).ToString() + (CurrentRow + i),
                        ((char)((int)ACol + j)).ToString() + (CurrentRow + i));


                        cell_range.Value2 = table.Rows[i - 1].ItemArray[j];
                        cell_range.Font.Bold = bold;
                        cell_range.Font.Italic = italic;
                    }
                }

                CurrentRow += TableRows;
            }
            else
                MessageBox.Show(
                    "Cannot output any text!\n" +
                    "Worksheed didnot created!",
                    "Error!!!", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
    public void SaveCurrentWorksheet(string filename)
    {
        try
        {
            ItsWorksheet.SaveAs(filename,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue,
                MissingValue);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }

    }
    public void CloseCurrentWorksheet()
    {
        if (WorkbookInitialized)
        {
            ItsWorkbook.Close(MissingValue,
                MissingValue,
                MissingValue);

            ItsApplication.Quit();

            WrbInitialization = false;
            WrsInitialization = false;
            AppInitialization = false;
        }
    }
    public bool ApplicationInitialized
    {
        get
        {
            return AppInitialization;
        }
    }
    public bool WorkbookInitialized
    {
        get
        {
            return WrbInitialization;
        }
    }
    public bool WorksheetInitialized
    {
        get
        {
            return WrsInitialization;
        }
    }
    ////////////////////////////////////////////////////////
    private _Application ItsApplication;
    private _Worksheet ItsWorksheet;
    private _Workbook ItsWorkbook;
    // Initialization flags
    private bool AppInitialization;
    private bool WrbInitialization;
    private bool WrsInitialization;
    // Positioning text in rows
    private int CurrentRow;
    ////////////////////////////////////////////////////////
    // Define static members of class
    private static object MissingValue = System.Reflection.Missing.Value;
    private static object EndOfDocument = "\\endofdoc";
}

您可以使用SetData方法将表格打印为Excel文件。

简单说明:

  1. 创建类的实例;
  2. 通过调用public void Initialize(bool visible)可见控制来确定世界应用程序是Excell窗口的可靠性。
  3. 致电CreateWorkbok;
  4. 创建新工作簿
  5. CreateWorksheet;
  6. 的工作表
  7. 使用工作表SetData - 打印表DataTable;
  8. 使用文字SetText
  9. 保存并关闭使用SaveCurrentWorksheetCloseCurrentWorksheet

    ExcelManager excel_manager = new ExcelManager()
    excel_manager.Initialize(true);
    excel_manager.CreateWorkbook();
    excel_manager.CreateWorksheet();
    
    excel_manager.SetText("Česnek!", 1, 0, 0);
    excel_manager.SetData(systemTable, 0, 0, 2);
    excel_manager.SetText("Лог консолі!", 1, 0, 3);
    

    电话结果:

    enter image description here

    或者您可以使用Open XML SDK for Office来支持Web应用程序中的多任务。

答案 1 :(得分:1)

我能在一天之后解决它 - csv和tab .txt文件解决方案:(在Core CLR下工作)

    public async Task<IActionResult> Export(string type)
    {
        string _OuputType = type.ToLower().Trim();  
        string _delimiter = _OuputType.Contains("csv") ? ";" : String.Empty;
        _delimiter = _OuputType.Contains("txt") ? "" : _delimiter;             

        IEnumerable<Material> data = await _context.Material.Include(m => m.Unit).ToListAsync(); 
        StringBuilder str = new StringBuilder();

        //file name
        string fileName = "Material-" + DateTime.Now.ToString("dd_MM_yyyy-H_mm_ss");

        //head
        str.Append("Name" + _delimiter + "\t");
        str.Append("AutoPlan" + _delimiter + "\t");
        str.Append("QuantityMinStock" + _delimiter + "\t");
        str.Append("QuantityMaxStock" + _delimiter + "\t");
        str.Append("QuantityPurchase" + _delimiter + "\t");
        str.Append("Unit" + _delimiter + "\t");
        str.Append("\r\n");

        //data
        foreach (Material m in data)
        {
            str.Append(m.id + _delimiter + "\t");
            str.Append(m.Name + _delimiter + "\t");
            str.Append(m.AutoPlan + _delimiter + "\t");
            str.Append(m.QuantityMinStock + _delimiter + "\t");
            str.Append(m.QuantityMaxStock + _delimiter + "\t");
            str.Append(m.QuantityPurchase + _delimiter + "\t");
            str.Append(m.Unit.LocalizedCode + _delimiter + "\t");
            str.Append("\r\n");
        }    

        //   int codepage = _cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture); == This is my service to get code page (example: 1250, or 1252 etc...)
        Encoding encode = Encoding.GetEncoding(_cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture));
        byte[] bytes = encode.GetBytes(str.ToString());


        if (_OuputType == "txt"){return File(bytes, "text/plain", fileName + ".txt");}
        return File(bytes, "application/msexcel", fileName + ".csv");
   }
相关问题