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

发布于 2024-08-18 06:40:59 字数 279 浏览 5 评论 0原文

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

我正在复制值,如下所示:

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

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

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

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.

I am copying the values like so:

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

永言不败 2024-08-25 06:40:59

下面是一些代码,用于将 A 列和 C 列格式化为 SpreadsheetGear for .NET 中的文本,它具有类似的 API Excel - 除了 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

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);

Disclaimer: I own SpreadsheetGear LLC

感情洁癖 2024-08-25 06:40:59

如果将单元格格式设置为文本优先添加带前导零的数值,则前导零将被保留,而不必通过添加撇号来扭曲结果。如果您尝试手动将前导零值添加到 Excel 中的默认工作表,然后将其转换为文本,则前导零将被删除。如果您先将单元格转换为文本,然后添加您的值,那就可以了。以编程方式执行此操作时也适用相同的原则。

        // Pull in all the cells of the worksheet
        Range cells = xlWorkBook.Worksheets[1].Cells;
        // set each cell's format to Text
        cells.NumberFormat = "@";
        // reset horizontal alignment to the right
        cells.HorizontalAlignment = XlHAlign.xlHAlignRight;

        // now add values to the worksheet
        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
            {
                DataGridViewCell cell = dataGridView1[j, i];
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
            }
        }

If you set the cell formatting to Text prior to adding a numeric value with a leading zero, the leading zero is retained without having to skew results by adding an apostrophe. If you try and manually add a leading zero value to a default sheet in Excel and then convert it to text, the leading zero is removed. If you convert the cell to Text first, then add your value, it is fine. Same principle applies when doing it programatically.

        // Pull in all the cells of the worksheet
        Range cells = xlWorkBook.Worksheets[1].Cells;
        // set each cell's format to Text
        cells.NumberFormat = "@";
        // reset horizontal alignment to the right
        cells.HorizontalAlignment = XlHAlign.xlHAlignRight;

        // now add values to the worksheet
        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
            {
                DataGridViewCell cell = dataGridView1[j, i];
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
            }
        }
安人多梦 2024-08-25 06:40:59

适用于我的 Excel Interop 解决方案:

myWorksheet.Columns[j].NumberFormat = "@";      // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "@"; // cell as a text

此代码应在将数据放入 Excel 之前运行。列号和行号从 1 开始。

更多细节。尽管已接受的参考 SpreadsheetGear 的回复看起来几乎正确,但我对此有两个担忧:

  1. 我没有使用 SpreadsheetGear。我对常规 Excel 感兴趣
    通过 Excel 互操作进行通信,无需任何第三方库,
  2. 我正在寻找按数字格式化列的方法,而不是使用
    范围如“A:A”。

Solution that worked for me for Excel Interop:

myWorksheet.Columns[j].NumberFormat = "@";      // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "@"; // cell as a text

This code should run before putting data to Excel. Column and row numbers are 1-based.

A bit more details. Whereas accepted response with reference for SpreadsheetGear looks almost correct, I had two concerns about it:

  1. I am not using SpreadsheetGear. I was interested in regular Excel
    communication thru Excel interop without any 3rdparty libraries,
  2. I was searching for the way to format column by number, not using
    ranges like "A:A".
她说她爱他 2024-08-25 06:40:59

在写入 Excel 之前需要更改格式:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight

Before your write to Excel need to change the format:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
尝蛊 2024-08-25 06:40:59

我最近也在与这个问题作斗争,并且我从上述建议中学到了两件事。

  1. 将 numberFormatting 设置为 @ 会导致 Excel 左对齐该值,并像文本一样读取它,但它仍然会截断前导零。
  2. 在开头添加撇号会导致 Excel 将其视为文本并保留零,然后应用默认文本格式,从而解决了这两个问题。

其误导性在于您现在在单元格中具有不同的值。幸运的是,当您复制/粘贴或导出到 CSV 时,不包含撇号。

结论:使用撇号,而不是数字格式来保留前导零。

I've recently battled with this problem as well, and I've learned two things about the above suggestions.

  1. Setting the numberFormatting to @ causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
  2. Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.

The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.

Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.

旧人九事 2024-08-25 06:40:59

使用您的WorkSheet.Columns.NumberFormat,并将其设置为字符串“@”,示例如下:

Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "@";

注意:此文本格式将适用于您的孔 Excel 工作表!

如果您希望特定列应用文本格式,例如第一列,您可以这样做:

workSheet.Columns[0].NumberFormat = "@";

或者这会将 woorkSheet 的指定范围应用到文本格式:

workSheet.get_Range("A1", "D1").NumberFormat = "@";

Use your WorkSheet.Columns.NumberFormat, and set it to string "@", here is the sample:

Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "@";

Note: this text format will apply for your hole excel sheet!

If you want a particular column to apply the text format, for example, the first column, you can do this:

workSheet.Columns[0].NumberFormat = "@";

or this will apply the specified range of woorkSheet to text format:

workSheet.get_Range("A1", "D1").NumberFormat = "@";
萧瑟寒风 2024-08-25 06:40:59
   if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
   {
      myWorksheet.Cells[i + 2, j].NumberFormat = "@";
   }
   if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
   {
      myWorksheet.Cells[i + 2, j].NumberFormat = "@";
   }
呆头 2024-08-25 06:40:59

我知道这个问题已经过时了,但我仍然愿意做出贡献。

应用 Range.NumberFormat = "@" 只是部分解决问题:

  • 是的,如果将焦点放在范围的单元格上,您将在格式菜单中读取文本
  • 是的,它将数据向左对齐
  • 但是如果您使用类型公式检查单元格中值的类型,它将返回1 表示数字

应用撇号表现得更好。它将格式设置为文本,将数据向左对齐,如果您使用类型公式检查单元格中值的格式,它将返回2含义文本

I know this question is aged, still, I would like to contribute.

Applying Range.NumberFormat = "@" just partially solve the problem:

  • Yes, if you place the focus on a cell of the range, you will read text in the format menu
  • Yes, it align the data to the left
  • But if you use the type formula to check the type of the value in the cell, it will return 1 meaning number

Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text

暗藏城府 2024-08-25 06:40:59
//where [1] - column number which you want to make text

ExcelWorksheet.Columns[1].NumberFormat = "@";


//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.

  //path were excel file is kept


     string ResultsFilePath = @"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";

            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
            ExcelApp.Visible = true;

            //Looping through all available sheets
            foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
            {                
                //Selecting the worksheet where we want to perform action
                ExcelWorksheet.Select(Type.Missing);
                ExcelWorksheet.Columns[1].NumberFormat = "@";
            }

            //saving excel file using Interop
            ExcelWorkbook.Save();

            //closing file and releasing resources
            ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(ExcelWorkbook);
            ExcelApp.Quit();
            Marshal.FinalReleaseComObject(ExcelApp);
//where [1] - column number which you want to make text

ExcelWorksheet.Columns[1].NumberFormat = "@";


//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.

  //path were excel file is kept


     string ResultsFilePath = @"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";

            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
            ExcelApp.Visible = true;

            //Looping through all available sheets
            foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
            {                
                //Selecting the worksheet where we want to perform action
                ExcelWorksheet.Select(Type.Missing);
                ExcelWorksheet.Columns[1].NumberFormat = "@";
            }

            //saving excel file using Interop
            ExcelWorkbook.Save();

            //closing file and releasing resources
            ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(ExcelWorkbook);
            ExcelApp.Quit();
            Marshal.FinalReleaseComObject(ExcelApp);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文