C#Excel Interop:如何格式化单元格以将值存储为文本

我从DataTable向Excel电子表格写入数字,如果数字本身长度小于5位数(例如395将存储为00395),所有这些数字都是5位数字,前面是0。

将这些数字inputExcel(使用C#)时,将它们存储为数字,并删除前面的0。 有没有什么办法可以格式化C#中的单元格,以便将值存储为文本而不是数字?

你可以SomeRange.NumberFormat = "@"; 或者如果你用一个'前缀'的值,并把它写入单元格Excel将把它作为一个数字存储为文本,并提供一个视觉提示。

这个答案刚刚解决了我们公司的一个软件的一个解决scheme的主要问题,我不得不检索显示的值,但是一旦我将它设置到新的表单中,它就被插入为一个数字。 解决scheme简单 我现在还不能投票,但下面是结果如何。

 for (int h = 1; h <= 1; h++) { int col = lastColl(sheets); for (int r = 1; r <= src.Count; r++) { sheets.Cells[r, col + 1] = "'"+src.Cells[r, h].Text.ToString().Trim(); } } 

//其中[1]是您要创build文本的列号

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

//如果要在工作簿中的所有工作表中格式化一个特定的列,请使用下面的代码。 除去轻微的变化,去除单页的循环。

//path是excel文件保存

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