Click here to Skip to main content
13,408,062 members (55,371 online)
Rate this:
Please Sign up or sign in to vote.
See more:

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);
Posted 23-Jan-13 1:39am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

(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.

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

tisdag, januari 01, 2013

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.180221.1 | Last Updated 25 Jan 2013
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100