将值从数据表复制到Excel工作表时,我丢失了前导零。这是因为Excel可能会将值视为数字而不是文本。
我在C#中创建了工作表,并且正在复制以下值:
myWorksheet.Cells[i + 2, j] = dtCustomers.Rows[i][j - 1].ToString();
如何将整个列或每个单元格设置为文本格式?一个相关的问题,如何myWorksheet.Cells[i + 2, j] 在Intellisense中强制显示样式属性?
myWorksheet.Cells[i + 2, j]
下面是一些代码,用于将SpreadsheetGear for .NET中的 A列和C列格式化为文本,其具有类似于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