c# - 在 C# 中将 Excel 列(或单元格)格式化为文本?

标签 c# excel export-to-excel

当我将值从数据表复制到 Excel 工作表时,我丢失了前导零。这是因为 Excel 可能会将这些值视为数字而不是文本。

我正在像这样复制值:

myWorksheet.Cells[i + 2, j] = dtCustomers.Rows[i][j - 1].ToString();

如何将整列或每个单元格格式化为文本?

一个相关的问题,如何转换 myWorksheet.Cells[i + 2, j] 以在 Intellisense 中显示样式属性?

最佳答案

下面是一些代码,用于将列 A 和 C 格式化为 SpreadsheetGear for .NET 中的文本,它具有类似于 Excel 的 API - 除了 SpreadsheetGear 通常是强类型的事实。弄清楚如何将其转换为使用 Excel/COM 应该不难:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

免责声明:我拥有 SpreadsheetGear LLC

关于c# - 在 C# 中将 Excel 列(或单元格)格式化为文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2067926/

相关文章:

c# - ASP.net Ajax 未知 Web 方法

arrays - 将整个数组作为字符串返回

vba - 在VBA中使用变量名调用函数

sql-server - 请求的 OLE DB 提供程序 Microsoft.ACE.OLEDB.16.0 未注册。如果未安装 32 位驱动程序,请以 64 位模式运行该包

c# 没有向 PHP 发送 json 请求

c# - WebRequest BeginGetResponse/EndGetResponse 在使用 Task.FromAsync 时抛出异常

c# - 合并空检查和模式匹配的 'if'语句时出错

vba - 对 Excel Vba 中的 DLL 函数调用进行故障排除

html - 以简单的方式导出到 Excel(但不是 CSV)

mysql - 使用 Ruby 将 mysql 结果导出到文件