Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Excel
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);
Posted 23-Jan-13 0:39am
rbitla347

1 solution

Rate this: bad
good
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.
 
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
 
Output:
2013-01-01
41275
#########
tisdag, januari 01, 2013
 
TL;DR
Use:
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?
  Permalink  
v2
Comments
ashrael2 at 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
0 CHill60 360
1 Sarvesh Kumar Gupta 238
2 OriginalGriff 193
3 Sergey Alexandrovich Kryukov 163
4 DamithSL 153


Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 25 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid