I'm reading an excel file with interop but I'm getting different values than I see on screen. I don't know what can be happening.
Excel that I'm reading:
When I read the cell E5 or E6 I'm getting the text "NUM VAGON", but what I see in screen is "Nº VAGON", the same with others rows and columns, different value of what I see and what I get.
There is no other worksheet so this is not the problem. If I copy all text in another excel it works fine.
The same applies with Value and Value2.
Here is my code:
xl.Application app = null;
try
{
//app = new Microsoft.Office.Interop.Excel.ApplicationClass();
app = new Microsoft.Office.Interop.Excel.Application();
//xl.Workbook theWorkbook = app.Workbooks.Open(eFile, 0, true, 5, "", "", true, xl.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xl.Workbook theWorkbook = app.Workbooks.Open(eFile);
//xl.Sheets sheets = theWorkbook.Worksheets;
//xl.Worksheet worksheet = (xl.Worksheet)sheets.get_Item(1);
xl.Worksheet worksheet = (xl.Worksheet)theWorkbook.Sheets[1];
xl.Range range = null;
range = worksheet.get_Range("E6", "E6");
//System.String titulo = (System.String)range.Cells.Value2;
System.String titulo = (System.String)range.Cells.Text;
I think .Text gives you the formatted cell content (and for some reason the Interop dll is transforming the N° into NUM).
You seem to have tried .Value2 (the commented line just above). Doesn't that give what you want? The Value property exists too but is almost the same as Value2.
This post explains the difference between Text, Value and Value2:
https://stackoverflow.com/a/17363466/6996150
Update:
How / where do you see that NUM text? When debugging? Or do you output it somewhere? Maybe the text is correct (N°) but formatted by the debugger or the tool you use to read your output?
Related
I have a Windows Forms application with 5 methods (each based off of the user clicking a button). In each method, I would like to open the same excel file the same way. However, in each method I want to select a different range on the worksheet. I tried creating a function to open the excel file rather than rewriting it 5 times...
// method to open Excel and load a the workbook based on date selected.
public Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> openExcel()
{
Microsoft.Office.Interop.Excel.Application excelObj = new Microsoft.Office.Interop.Excel.Application();
string fileName = #"C:\Users\" + userName + #"\Documents\Visual Studio 2015\Projects\ProgramForMom\ProgramForMom\bin\Debug\Excel Files\" + frm2.year.Text + " Expenses";
Workbook wb = excelObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
wb.Activate(); // Activates file.
Worksheet ws = wb.Worksheets[frm2.month.Text];
ws.Activate();
return Tuple.Create(excelObj, wb, ws);
}
All that works fine.
I tried referenced this function in one of the methods...
var excelObj = openExcel();
Workbook wb = openExcel();
Worksheet ws = openExcel();
var cellValue = ws.Range["A1"].Value2;
and I get an error saying...
"Cannot implicitly convert type 'System.Tuple' to 'Microsoft.Office.Interop.Excel.Workbook'. An explicit conversion exists (are you missing a cast?)"
I get the same error for the worksheet. It says the same exact thing just substitutes the word worksheet in place of workbook.
Can you please explain what I have done wrong? Thank you.
var result = openExcel();
var excelObj = result.Item1;
Workbook wb = result.Item2;
Worksheet ws = result.Item3;
var cellValue = ws.Range["A1"].Value2;
You have a mismatch between the return type of your method (which is a Tuple) and the type of the variables in which you want to catch the output of openExcel
it should look more like this
Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> allThreeInOne = openExcell();
then you can try and fiddle everything apart... OR
what you also can do is to access the value right at the point of the function call:
var excelObj = openExcel().Item1;
Workbook wb = openExcel().Item2;
Worksheet ws = openExcel().Item3;
this way you would assign exactly the matching type to the variables
EDIT:
Tha latter solution is not advisable since you would unnecessarily open the file 3 times just to get the result that you would have gotten already from the first call,as Joel Coehoorn correctly pointed out.
fiddling the tuple apart would be the way to go:
var excelObj = allThreeInOne.Item1;
Workbook wb = allThreeInOne.Item2;
Worksheet ws = allThreeInOne.Item3;
I'm having problems changing a link in a workbook that contains a moved sheet.
I move two worksheets from a workbook (tempworkbook) called "Analysis Template.xlsx" into a new workbook (_wb), at which point, I then want to change the link that's in those two sheets from tempworkbook to refer to the new workbook they've just been moved into, yet my changelink code seems to have no effect, and i'm positive i've got the paths correct. Why is this? It's not returning any error, it's just when I check the link in excel itself, its still pointing to the original "Analysis Template" workbook.
As I want this to run in the background, i've disabled a few things within the application, could this be why?
_xl.Visible = false;
_xl.UserControl = true;
_xl.DisplayAlerts = false;
_xl.Interactive = false;
_xl.ScreenUpdating = false;
Microsoft.Office.Interop.Excel.Workbook tempworkbook = _xl.Workbooks.Open(System.IO.Directory.GetCurrentDirectory() + "\\Analysis Template.xlsx", 0, false, 1, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, 9, true, false, 0, true, false, false); //open template XLS file
Microsoft.Office.Interop.Excel.Worksheet tmp1 = (Microsoft.Office.Interop.Excel.Worksheet)tempworkbook.Sheets["Data"]; //extract 1st worksheet to move
Microsoft.Office.Interop.Excel.Worksheet tmp2 = (Microsoft.Office.Interop.Excel.Worksheet)tempworkbook.Sheets["Evaluation"]; //extract 2nd worksheet to move
tmp1.Move(Missing.Value, _wb.Sheets[7]); //move 1st worksheet into new workbook
tmp2.Move(Missing.Value, _wb.Sheets[8]); //move 2nd worksheet into new workbook
_wb.ChangeLink(tempworkbook.FullName, _wb.FullName, Microsoft.Office.Interop.Excel.XlLinkType.xlLinkTypeExcelLinks); //change link from template workbook to refer to new workbook
The documentation suggests that you probably need to do a loop over all link sources, and update them each individually.
If you were looking to debug the problem, I would strongly suggest you at least confirm that tempworkbook.FullName is the same as the output of LinkSources(_wb).
Haven't done it personally, just trying to help.
I am developing a game in Visual Studio 2008, C# Windows Forms Application. It is a word game. For that I read set of words from excel file named "Dictionary.xlsx".
`Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook theWorkbook;
Excel.Sheets sheets;
Excel.Worksheet worksheet;
public Excel.Range range;
string str;
//in the load event of the form
theWorkbook = ExcelObj.Workbooks.Open(#"C:\Documents and Settings\Administrator\Desktop\Dictionary.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
sheets = theWorkbook.Worksheets;
worksheet = (Excel.Worksheet)sheets.get_Item(1);
range = worksheet.UsedRange;
//reading the contents from excel file and adding into ListBox "listBox1"
for (int rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
str1 = (string)(range.Cells[rCnt, 1] as Excel.Range).Value2;
listBox1.Items.Add(str1.ToUpper());
}`
This "Dictionary.xlsx" contains 51899 words. So it takes 5 minutes to read the contents into a ListBox "listBox1".
So I added that "Dictionary.xlsx" file into my application's Resource by right clicking Resources->Add->Existing item->Dictionary.xlsx in the Solution Explorer. When I searched, I came to know that the key to access resource files is to use ResourceManager class from System.Resources namespace.
But I have no idea about how to instantiate ResourceManager class. When I looked at msdn, I can't understand it.
Now how can I read or refer to the words in my dictionary in my project resource?
Does reading from Resource file take less time than reading from external file?
Thank you:-)..
Suppose I have an excel file containing 4 sheets, Sheet 1, Sheet 2 and so on. I need to read data from a List object, truncate all the data of Sheet 1, and write the data from the List object into that Sheet 1, without affecting any other sheet..
This is what I have been trying..
string pathFileSource = "C:\\Temp\\Output.xls";
string pathFileDestination = "C:\\Temp\\Performance Testing.xls";
Excel.Application excel = new Excel.Application();
Excel.Workbook wbSource = excel.Workbooks.Open(pathFileSource, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Workbook wbDestination = excel.Workbooks.Open(pathFileDestination, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Missing.Value);
Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
// Select used Range, paste value only
WorksheetDestination.UsedRange.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationAdd, false, false);
wbSource.Close();
wbDestination.Save();
wbDestination.Close();
//Quit application
excel.Quit();
Although I am getting alerts stating that the data has been added to Clipboard, the destination file is not getting updated with the correct data. Any pointers as to where I am going wrong?
I will be really grateful if someone can provide an actual working code, and not pseudocodes.
This is (default)normal mode of MS Excel to edit one worksheet at a time and separately or independently of other worksheets.
However, if you have created a Worksheet Group by selecting worksheet tabs, then first of all, you have to un-group the worksheets. Then you can handle every worksheet independently.
I hope this may help!
You can make a Group of worksheets by:
Press and hold CTRL key and click on worksheet tabs(left button click).
And un-group your worksheets by the same process again.
thanks in advance for your help. I want to loop through all worksheets in a workbook. Unfortunately, I don't know how many worksheets there are in a given workbook. Right now I use the following technique to enumerate through all worksheets:
Excel.Worksheet xlWorkSheet1;
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Worksheet xlWorkSheet2;
xlWorkSheet2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
Excel.Worksheet xlWorkSheet3;
xlWorkSheet3 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
Is there a method that returns the number of worksheets in a workbook?
Use Excel.Workbook and then you can use the Workbook.Sheets.Count() in a for or while loop.
The Worksheets property has a collection of the worksheets .
foreach (Excel.Worksheet xlworksheet in xlworkbook.Worksheets)
{
//xlworksheet code here
}
Or, get the count value and use a for loop.
Googling this results in either this page, or several others where you have to use VBA or C# or start mucking about in the Name Manager in Excel.
Anyone looking for a quick and dirty solution:
Open the xlsx file with 7zip and navigate to xl\worksheets.
In there you should see all the sheets, and if you select those 7zip will count them for you.
Insert a module in the workbook you want to count the total sheets of,
Then type the below code and hit run
Public Sub CountWorksheets()
MsgBox "Total Sheets count:" & Application.Sheets.Count
End Sub
You'll get a relevant output like below
We can now use: int Workbook.Sheets.Count
I use this code:
//Create application.
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
//Opening excel book
Workbook ObjWorkBook = ObjExcel.Workbooks.Open(excelFileLocation, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Getting sheets count
int sheetsCount = ObjWorkBook.Worksheets.Count;
For this code to work, you need to install the package using NuGet - Microsoft.Office.Interop.Excel