Workbooks.Open vs OLEDBConnection fails to open workbook - c#

I'm getting error:
Excel cannot open the file 'FILE.xlsx' because the file format or
file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file.
I suspect the reason is due to the fact that on File.xlsx I have a OleDBConnection using it and that later in the same code I call the Interop function Open of Excel on that file. Can someone confirm my theory?
public ExcelWorkbook(string file)
{
fileName = file;
using (var workbookConnection = new OleDbConnection(String.Format(Resource.ExcelConnectionString, file)))
{
workbookConnection.Open();
tabNames = GetDataTabsName(workbookConnection);
foreach (string tabName in tabNames)
{
var newExcelTab = new ExcelTab(workbookConnection, file, tabName);
excelTabs.Add(tabName, newExcelTab);
}
}
}
Then my function GetDataTabsName(workbookConnection);
private List<string> GetDataTabsName(OleDbConnection workbookConnection)
{
var tabsName = new List<string>();
var tabName = "";
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
Excel.Workbook workbook = excelApp.Workbooks.Open(workbookConnection.DataSource, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
....some more code
The Open fails here...and my best guess is that because an OleDBConnection is exist on that file??

After further testing, it turned out that my guess was right. So having an OleDBConnection open on a worksheet cannot be opened simultaneously with Microsoft.InterOp

The third parameter to Workbooks.Open specifies whether or not the work should be opened in read-only mode. If the interop connection is only for reading, try setting that value to true. If the OleDb connection can be read-only, add ReadOnly=true; to your connection string.

Related

C# cannot read from read-only Excel file

I have a folder on my PC containing multiple Excel spreadsheets that are all marked as read-only.
The folder is synced to my company's Sharepoint via OneDrive.
When I try to programmatically read data from one of these sheets via Microsoft.Office.Interop.Excel, I keep getting the You cannot use this command on a protected sheet error.
Here's the code I use to open the file:
public ExcelReader(String filePath)
{
this.filePath = filePath;
FileName = filePath.Substring(filePath.LastIndexOf("\\")+1);
app = new Excel.Application();
app.DisplayAlerts = false;
workbook = app.Workbooks.Open(filePath, false, true); //open in read only
}
public void openSheet(String sheet)
{
SheetName = sheet;
worksheet = workbook.Sheets[sheet];
Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
ColumnsTotal = last.Column;
RowsTotal = last.Row;
}
The line that throws the exception is Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);.
I figured that since I explicitly tell the Workbook to open in Read-only mode, and since I never modify the content of these files, the fact that files are read-only shouldn't be a problem.
What am I doing wrong here? How do I read the content of these files without unprotecting them (I can't do that for security reasons)?

How to open an Excel file in PrintPreview without suspending the code

I'm new to C#/OpenXML and could not find an answer to this. Apologies in advance if it's a stupid question...
Basically, I am writing an application that creates Excel files from an input string. This input string may contain information about multiple files that need to be created and opened in the print preview dialog simultaneously. However, using the following function, the code is suspended on the printpreview.show() method as it waits for the user to close the preview.
public static void ExcelOpen(string fileName)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, false, 0, false, false);
Excel.Worksheet ws = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrintPreview].Show();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
return;
}
How can I avoid this and make sure the window stays opened in print preview but my program continues to run and create/display further files?

Returning Excel variables C#

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;

Load an Excel file using implicit typing

class ExcelHandling
{
public static void NewExcelFile(){
frmMain._frmMain.EXCEL_FILE = new Excel.Application();
var excelApp = frmMain._frmMain.EXCEL_FILE as Excel.Application;
excelApp.Workbooks.Add();
excelApp.Visible = true;
}
public static void LoadExcelFile()
{
FileStream load = File.Open(#"F:\dsa.xlsx", FileMode.Open, FileAccess.Write);
var excelApp = load as Excel.Application;
frmMain._frmMain.EXCEL_FILE = excelApp;
excelApp.Visible = true;
}
}
The above shown LoadExcelFile() method doesn't work.
What is the correct way of loading an existing excel file into a variable? I've tried a few things, but to no avail. The NewExcelFile() method works like a charm - it creates a new Excel file, stores it into the EXCEL_FILE global variable so I can manipulate it thereafter and shows it. I want the load function to do the same but with an existing excel file.
Here is an example of opening an existing Excel spreadsheet using the Microsoft.Interop library:
var xlApp = new Microsoft.Office.Interop.Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open("PathAndNameOfMyFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
The overload parameters are fairly vague in documentation, but unfortunately required. Intellisense should give you some idea of the values and their meaning.
Your issue was that you were using a FileStream and then trying to let the library figure out what that stream contained. This will utilize the interop library to open the file and handle the data properly.
I really like LinqToExcel. You can use NuGet Package Mgr in Visual Studio to add it https://www.nuget.org/packages/LinqToExcel . Documentation is #https://code.google.com/p/linqtoexcel/ (with a demo video)

C# Excel Interop: Opening and Showing CSV file

Hey I'm writing a wrapper for the excel interop, I want to be able to open a csv file in excel and show it to the user. I've got the basics down, but when i set visible to true and excel shows up, all columns are jammed into the first, and the separating commas are showing.
here's my helper.
public MyExcel(string filePath, bool readOnly)
{
_app = new Excel.Application();
_workbooks = _app.Workbooks;
_workbook = _workbooks.Open(_filepath, 0, _readOnly, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", !_readOnly, false, 0, true, true, true);
}
public void Show()
{
_app.Visible = true;
}
any suggestions?
When i open the file by double clicking Excel processes everything properly.
You will need to use the OpenText method, instead of Open, if you want Excel to parse for delimiters. Details: http://msdn.microsoft.com/en-us/library/bb223513%28v=office.12%29.aspx
An example in C#: http://msdn.microsoft.com/en-us/library/c9838808.aspx
It is MUCH easier than that if all you want to do is open the file...
Process proc = new Process();
proc.StartInfo = new ProcessStartInfo("excel.exe", "output.csv");
proc.Start();

Categories