将Excel列(或单元格)格式化为C#中的文本? [英] Format an Excel column (or cell) as Text in C#?

查看:149
本文介绍了将Excel列(或单元格)格式化为C#中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am losing the leading zeros when I copy values from a datatable to an Excel sheet. That's because probably Excel treats the values as a number instead of text.

我在C#中创建了工作表,我正在复制如下值:

I created the worksheet in C# and I am copying the values like so:

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

如何将整个列或每个单元格格式化为文本?一个相关的问题,如何转换 myWorksheet.Cells [i + 2,j] 在Intellisense中显示一个样式属性?

How do I format a whole column or each cell as Text? A related question, how to cast myWorksheet.Cells[i + 2, j] to show a style property in Intellisense?

推荐答案

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

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with 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

Disclaimer: I own SpreadsheetGear LLC

这篇关于将Excel列(或单元格)格式化为C#中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆