Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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.

C#
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);
Posted

1 solution

(EDIT: 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:
VB
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


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

TL;DR
Use:
VB
Format(a.Value, a.NumberFormat)

where a is a Range. This creates a string representation of the cells value with format applied. Does that answer your question?
 
Share this answer
 
v2
Comments
ashrael2 10-Feb-14 13:46pm    
What namespace is Format from? Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900