C# Excel Interop: Opening and Showing CSV file - c#

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();

Related

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?

C# read excel cell getting different value that seen on screen

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?

Unable to change link in Excel workbook

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.

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)

Workbooks.Open vs OLEDBConnection fails to open workbook

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.

Categories