【问题标题】:Set Excel Column to Text (Exporting Data in DataGridView to Excel)将 Excel 列设置为文本(将 DataGridView 中的数据导出到 Excel)
【发布时间】:2016-02-15 16:58:00
【问题描述】:

我正在将数据从 DataGridView 导出到 Excel。一切正常,但是当列中的数据具有例如:000115455 时,Excel 会忽略“0”并插入 115455。我接下来尝试:

  • 在填充DataGridView之前格式化DataTable中的列
  • 将从数据库检索的数据转换为 VARCHAR。
  • 在填充后格式化 DataGridView 中的列。
  • 在我的方法中使用 Range.EntireColumn、Range.Cells.NumberFormat 等方式。

这些都不行!

下面是导出到excel并保存文件的一段代码

ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelLibro = ExcelApp.Workbooks.Add(misDatos);
ExcelHoja = (Excel.Worksheet)ExcelLibro.Worksheets.get_Item(1);
Excel.Range rangoHoja = (Excel.Range)ExcelHoja.Cells[1, 1];
rangoHoja.Select();
ExcelHoja.PasteSpecial(rangoHoja, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
ExcelLibro.SaveAs(opcionSFD.FileName, 
                                  Excel.XlFileFormat.xlWorkbookNormal,
                                  misDatos,
                                  misDatos, 
                                  misDatos, 
                                  misDatos, 
                                  Excel.XlSaveAsAccessMode.xlExclusive, 
                                  misDatos, 
                                  misDatos, 
                                  misDatos, 
                                  misDatos,
                                  misDatos);

                ExcelApp.DisplayAlerts = true;
                ExcelLibro.Close(true, misDatos, misDatos);
                ExcelApp.Quit();

我能做什么?

【问题讨论】:

    标签: c# excel winforms datagridview


    【解决方案1】:

    这对我有用:

    在调用ExcelHoja.PasteSpecial(...)之前添加这一行:

    rangoHoja.NumberFormat = "@";
    

    这会将单元格的格式设置为文本

    ...
    rangoHoja.Select();
    rangoHoja.NumberFormat = "@"; //Added Line    
    ExcelHoja.PasteSpecial(...);
    ...
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 2014-04-09
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多