读取excel单元格文本及其应用的格式 [英] Read excel cell text along with its format applied

查看:126
本文介绍了读取excel单元格文本及其应用的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个单元格,其中已经应用了自定义格式并且不是自动调整。

我想要读取该单元格的内容及其格式。

我尝试过cell.value但是它给出了没有格式的普通值,如果我使用cell.text然后它给出###如果单元格是不自动调试,我不想改变列的宽度。

请建议是否有办法做到这一点,或使用单元格格式化字符串数字格式

请帮助,任何帮助都会有很大帮助。



下面是我试过的代码。



Hi,

I have a cell in which has got custom format applied to it and is not autofit.
I want to read content of that cell along with its format.
I have tried cell.value but then it give plain value without format, and if i use cell.text then it gives ### if the cell is not autofit and i dont want to change the width of the column.
Please suggest if there is way to do this, or to format the string using the cell NumberFormat
Please help, any help would be greatly appreaciated.

Below is the code that i have tried.

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();                Microsoft.Office.Interop.Excel.Workbook wbExcel = xlApp.Workbooks.Open("D:\\Test.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wsSheet = (Microsoft.Office.Interop.Excel.Worksheet)wbExcel.Worksheets[1];
Range excelRange = (Range)(wsSheet.Cells[1, 1]);
DateTime excelDate = (DateTime)excelRange.get_Value(Type.Missing);
string strValue = wsSheet.Cells[1, 1].Value2.ToString();
string strText = wsSheet.Cells[1, 1].text;
wbExcel.Close(false, Type.Missing, Type.Missing);

推荐答案

(编辑:对不起,下面的示例解决方案是用VBA编写的。应该可以直接转换为c#)



获取值并格式化使用单元格数字格式。



示例:

单元格(1,1)输入值2013-01-01。



我使用本地数字格式,看起来像这样:

tisdag,januari 01,2013​​



缩小列,显示#######。



运行此宏:

( Sorry, example solution below is written in VBA. Should be straightforward to convert to c#)

Get the value and format it using the cells number format.

Example:
Cell(1,1) has the value "2013-01-01" entered.

I apply a local number format so it looks like this:
"tisdag, januari 01, 2013"

I shrink the column so "#######" is displayed.

Run this macro:
Sub codeproject()
    Dim a As Range
    Set a = ActiveSheet.Cells(1, 1)
    Debug.Print a.Value
    Debug.Print a.Value2
    Debug.Print a.Text
    Debug.Print Format(a.Value, a.NumberFormat)
End Sub





输出:

2013-01 -01

41275

#########

tisdag,januari 01,2013



TL; DR

使用:



Output:
2013-01-01
41275
#########
tisdag, januari 01, 2013

TL;DR
Use:

Format(a.Value, a.NumberFormat)



其中a是一个范围。这将创建应用了格式的单元格值的字符串表示形式。这会回答你的问题吗?


where a is a Range. This creates a string representation of the cells value with format applied. Does that answer your question?


这篇关于读取excel单元格文本及其应用的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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