简体   繁体   English

将Excel列设置为文本(将DataGridView中的数据导出到Excel)

[英]Set Excel Column to Text (Exporting Data in DataGridView to Excel)

I'm exporting data from DataGridView to Excel. 我正在将数据从DataGridView导出到Excel。 Everything works great but when a data in columns have, for example: 000115455, Excel is ignoring the '0' and inserting 115455. I try next: 一切都很好,但是当列中的数据具有例如000115455时,Excel将忽略'0'并插入115455。我尝试下一个:

  • Format the column in DataTable before Fill DataGridView 在填充DataGridView之前格式化DataTable中的列
  • Casting data retrieve from database as VARCHAR. 从数据库检索的转换数据为VARCHAR。
  • Format the column in DataGridView after Fill. 填充后,格式化DataGridView中的列。
  • Using Range.EntireColumn, Range.Cells.NumberFormat and other ways in my method. 在我的方法中使用Range.EntireColumn,Range.Cells.NumberFormat和其他方式。

None of this works! 这些都不行!

Below the piece of code that export to excel and save the file 在导出到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();

What I can do? 我可以做什么?

This works for me: 这对我有用:

Before call ExcelHoja.PasteSpecial(...) add this line: 在调用ExcelHoja.PasteSpecial(...)之前,添加以下行:

rangoHoja.NumberFormat = "@";

This sets cell's format to Text . 这会将单元格的格式设置为Text

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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM