Writing to an existing Excel File using c# - c#

I am trying to open (or create a new xls) Excel file and write some values to it. Although, the program below works just fine if I simply create a new xls file, I encounter the some problem in line
**mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);**
Here's the error:
'LOG.xls' cannot be accessed. The file may be corrupted, located on a server that is not responding, or read-only.
It's not read-only, it's not corrupted(because sometime the file is created on Run Time).
What is the problem then?
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
private void btnSignIn_Click ( object sender, EventArgs e )
{
string path = "D:\\LOG.xls";
if(!File.Exists(path))
{
File.Create (path);
}
oXL = new Microsoft.Office.Interop.Excel.Application ();
oXL.Visible = true;
oXL.DisplayAlerts = false;
//error on this line
mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item ("Sheet1");
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
for ( int index = 1; index < 15; index++ )
{
mWSheet1.Cells [rowCount + index, 1] = rowCount + index;
mWSheet1.Cells [rowCount + index, 2] = "New Item" + index;
}
mWorkBook.SaveAs (path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close (Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
}

The using of File.Create is not appropriate here. It returns a (Blank) FileStream, not an Excel File (Define the path with .xls will not create an Excel File...).
And as you do not close and dispose it, you have an exception when you try to open it because it is already in use (and you will have an exception in any way even if you release it, because you have not create an Excel file at this stage).
So if the workbook exists, you can open it by using oXL.Workbooks.Open.
If the workbook does not exist, YOU HAVE to create it by using: oXL.Workbooks.Add() and then you call mWorkBook.SaveAs(...) method to really create it.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
string path = "D:\\LOG.xls";
if (!File.Exists(path))
{
mWorkBook = oXL.Workbooks.Add;
}
else
{
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
}
(Hope the VB=>C# is correct!)
And in your SaveAs method, you will have to set the correct FileFormat if you want to create a specific version of Excel file (again set .xls in the path is not enough...)
Optional Object. The file format to use when you save the file. For a
list of valid choices, see the FileFormat property. For an existing
file, the default format is the last file format specified; for a new
file, the default is the format of the version of Excel being used.
Hope this helps.

If the workbook does not exist, the better way to create one would be as such:
Excel.Workbook newWorkbook = excelApplication.Workbooks.Add();
File.Create() returns an instance of FileStream, which you need to close if you want to access the file. You can change..
if(!File.Exists(path))
{
File.Create (path);
}
to
if(!File.Exists(path))
{
File.Create (path).Close();
}

Related

C# Saving to Excel issue [duplicate]

I am in the process of writing a module to export a DataTable to Excel using Microsoft.Office.Interop.Excel but before starting in earnest I want to get the very basics working: open file, save as, and close.
I have succeeded in opening and saving a file with the .xls extension, but saving with the .xlsx extension does not work. It writes the .xlsx file, but when I try to open it I get the following error:
Excel cannot open the file 'SomeFile.xlsx' because the file format is not valid. Verify that file has not been corrupted and that the file extension matched the format of the file.
The code I use to open, save and close the files is:
Excel.Application excelApplication = new Excel.Application();
//excelApplication.Visible = true;
//dynamic excelWorkBook = excelApplication.Workbooks.Add();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
//Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
int rowIndex = 1; int colIndex = 1;
excelApplication.Cells[rowIndex, colIndex] = "TextField";
// This works.
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xls", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// This does not!?
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xlsx", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
I have also tried the file format Excel.XlFileFormat.xlExcel12 in place of Excel.XlFileFormat.xlWorkbookNormal but this does not even write instead throwing the COMException:
Exception from HRESULT: 0x800A03EC
Any help resolving this would be most appreciated.
Edit: I have now also tried:
excelWorkBook.SaveAs("C:\\MyExcelTestTest", Excel.XlFileFormat.xlExcel12,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
Missing.Value is found in the System.Reflection namespace.
Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.
When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)
Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

How to read cell values that are dynamically generated using macros in c#?

I have an excel file in which some cell values are generating dynamically using macro.
File is also read-only.
I have to read these dynamically generated values using c# code.
Use following macro code to generate cell values:
**Sub abc()
Range("E5").Value = "string"
Range("E6").Value = 2
End Sub**
Thank You...!
Check if you need to connect to already opened excel file.
If you use excelApp.Workbooks.Open, it is not reflecting sheet data updated by macros.
Instead, try BindToMoniker method as follows:
private void btnGetXLSValue_Click(object sender, EventArgs e)
{
object _row = 5;
object _column = 5;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook ;//= excelApp.Workbooks.Open(#"C:\July.xlsm", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get a reference to the Workbook object by using a file moniker.
//The xls was saved earlier with this file name.
excelWorkbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(#"C:\July.xlsm");
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "July 2015";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.UsedRange;
string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).get_Value(range).ToString();
MessageBox.Show(sValue);
}

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

I am in the process of writing a module to export a DataTable to Excel using Microsoft.Office.Interop.Excel but before starting in earnest I want to get the very basics working: open file, save as, and close.
I have succeeded in opening and saving a file with the .xls extension, but saving with the .xlsx extension does not work. It writes the .xlsx file, but when I try to open it I get the following error:
Excel cannot open the file 'SomeFile.xlsx' because the file format is not valid. Verify that file has not been corrupted and that the file extension matched the format of the file.
The code I use to open, save and close the files is:
Excel.Application excelApplication = new Excel.Application();
//excelApplication.Visible = true;
//dynamic excelWorkBook = excelApplication.Workbooks.Add();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
//Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
int rowIndex = 1; int colIndex = 1;
excelApplication.Cells[rowIndex, colIndex] = "TextField";
// This works.
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xls", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// This does not!?
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xlsx", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
I have also tried the file format Excel.XlFileFormat.xlExcel12 in place of Excel.XlFileFormat.xlWorkbookNormal but this does not even write instead throwing the COMException:
Exception from HRESULT: 0x800A03EC
Any help resolving this would be most appreciated.
Edit: I have now also tried:
excelWorkBook.SaveAs("C:\\MyExcelTestTest", Excel.XlFileFormat.xlExcel12,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
Missing.Value is found in the System.Reflection namespace.
Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.
When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)
Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

C# excel close process still left

I am open and close an excel book fro mC# like this
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
try
{
excelWorkbook = oXL.Workbooks.Open(MyFile,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
.....
....
....
excelWorkbook.Save();
excelWorkbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Type.Missing, Type.Missing);
oXL.Quit();
excelWorkbook = null;
oXL = null;
}
catch { }
But there is stil lan EXCEL.EXE process left running in the task list, why ?
how do I "kill" everything about excel when I am done ?
Is it not enough with ".Quit()" and put the reference to null ?
or is there some magic reference left in the C# heap somewhere that have not been
dereferenced ?
/Stefan
Try this..
oXL.quit()
// Note, oXL still points to excel
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oXL)
oXL = Nothing

C#: How to access an Excel cell?

I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.
Currently I am at this stage with the following code but still I am getting errors:
Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
// is there already such a file ?
if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
{
// then go and load this into excel
Microsoft.Office.Interop.Excel.Workbooks.Open(
"C:\\csharp\\errorreport1.xls", true, false,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
else
{
// if not go and create a workbook:
newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
(Microsoft.Office.Interop.Excel._Worksheet)
newWorkBook.Worksheets.get_Item(1);
}
i++;
j = 1;
j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
+ rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";
These are the top 2 errors I am getting:
Error 1 An object reference is required for the nonstatic field, method, or
property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
object, object, object, object, object, object, object, object, object,
object, object, object, object)'
Error 2 The name 'newWorkbook' does not exist in the current context
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
I think, that you have to declare the associated sheet!
Try something like this
objsheet(1).Cells[i,j].Value;
How I work to automate Office / Excel:
Record a macro, this will generate a VBA template
Edit the VBA template so it will match my needs
Convert to VB.Net (A small step for men)
Leave it in VB.Net, Much more easy as doing it using C#
Try:
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();
oSheet.Cells[3, 9] = "Some Text"
Simple.
To open a workbook.
Use xlapp.workbooks.Open()
where you have previously declared and instanitated xlapp as so..
Excel.Application xlapp = new Excel.Applicaton();
parameters are correct.
Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.
This works fine for me
Excel.Application oXL = null;
Excel._Workbook oWB = null;
Excel._Worksheet oSheet = null;
try
{
oXL = new Excel.Application();
string path = #"C:\Templates\NCRepTemplate.xlt";
oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows, "", true, false,
0, true, false, false);
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[2, 2] = "Text";
You can use the below code; it's working fine for me:
newWorkbook = appExcel.Workbooks.Add();

Categories