My code is as follows
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange;
These are the only variables used in my function
foreach (Excel.Worksheet XLws in xlWorkbook.Worksheets)
{
// do some stuff
xlApp.UserControl = false;
if (xlRange != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlRange);
if (xlSheet != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet);
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlRange = null;
xlSheet = null;
xlWorkbook = null;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
}
But still I get EXCEL.EXE in Task Manager
Please help?
Kill the excel process which has empty value for MainWindowTitle. Below is an example source code.
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close(null, null, null);
oXL.Quit(); //MainWindowTitle will become empty afer being close
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWB);
Process[] excelProcesses = Process.GetProcessesByName("excel");
foreach (Process p in excelProcesses)
{
if (string.IsNullOrEmpty(p.MainWindowTitle)) // use MainWindowTitle to distinguish this excel process with other excel processes
{
p.Kill();
}
}
}
catch (Exception ex2)
{
}
You've got an implicit object left open. Try this
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Open(file);
....
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbooks);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
....
OK... I hope this helps... it took me forever to tweak this to get it to work just so...
Here is my entire function (VB -- but the C# code for the tricky stuff is in there (thanks to too many other stackoverflow giants who helped me get this far!)
Private Function ImportWorksFile() As Integer
Dim EndofSheet As Boolean
Dim BlankRowCounter As Integer
Dim rr As RowResult
Dim SecCount As Integer = 0
Dim SecRow As SecurityRow
Dim uf As New UtilFunctions
'If this has already been run, the instance of the excel object would have been 'killed' and needs to be reinstantiated
If blnExcelProcessKilled Then 'Global boolean var
xlApp = New Excel.Application()
blnExcelProcessKilled = False
End If
Dim excelProcess(0) As Process
excelProcess = Process.GetProcessesByName("excel")
Dim tmp As Excel.Workbooks
Try
tmp = xlApp.Workbooks
xlWorkBook = tmp.Open(WorkingFileName)
Catch ex As Exception
MessageBox.Show("There was a problem opening the workbook - please try again", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
End Try
Using dc As New AFLData(CurAFLApp, True)
Dim cmd As SqlCommand = DefineCommand()
cmd.CommandType = CommandType.StoredProcedure
For Each ws As Excel.Worksheet In xlWorkBook.Worksheets
Dim row As Integer = 1
EndofSheet = False
BlankRowCounter = 0
If ImpCols.ContainsKey(ws.Name) Then
SecRow = New SecurityRow(ImpCols(ws.Name))
Do Until EndofSheet
Try
SecRow.NewRow(ws.Rows(row))
rr = SecRow.IsValidRow
If rr = RowResult.Valid Then
' read this row and process
With cmd
.Parameters("#AcctDate").Value = FileDate
.Parameters("#NewSub").Value = SecRow.GetStrCell("newsub")
RunProcedure(cmd)
End With
SecCount += 1
BlankRowCounter = 0
Else
BlankRowCounter += rr
End If
Catch ex As Exception
MessageBox.Show("There was a problem with row: " & row & " in workbook " & ws.Name)
End Try
' if we've counted 50 blank A column values in a row, we're done.
If BlankRowCounter <= -50 Then
EndofSheet = True
End If
row += 1
Loop
End If
Next
End Using
Try
xlWorkBook.Close(SaveChanges:=False)
xlApp.Workbooks.Close()
xlApp.Quit()
'// And now kill the process. C# Version (for reference)
'if (processID != 0)
'{
' Process process = Process.GetProcessById(processID);
' process.Kill();
'}
' Reversed the order of release per http://stackoverflow.com/questions/12916137/best-way-to-release-excel-interop-com-object
Catch ex As Exception
MessageBox.Show("There was a problem CLOSING the workbook - Please double check that the data was imported correctly. ", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
Finally
releaseObject(tmp)
releaseObject(xlWorkBook)
releaseObject(xlApp)
If Not excelProcess(0).CloseMainWindow() Then
excelProcess(0).Kill()
blnExcelProcessKilled = True
End If
End Try
Return SecCount
End Function
Public Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
'Not sure if the following line helps or hinders -- seems to lock things up once in a while
'GC.WaitForPendingFinalizers()
End Try
End Sub
Try :
xlWorkbook.Close(false); // if you Workbook should not be saved
instead of :
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlWorkbook = null;
Related
I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.
I am having a ridiculously hard time with this, but I need to be able to connect to an open excel file using Interop and then write to that file.
The file is opened by an outside process and then this application comes in later to write to the workbook. I can get it to open a file and write to the active workbook. but I can't find a way to connect to a previous workbook and write.
I had been using Marshal.GetActiveObject but I will soon be running the application on a computer with multiple files open and need to write to one that will most likely not bee the active one.
Update :
System.Runtime.InteropServices.Marshal.BindToMoniker can be used to access file that is opened in Excel, or opens it if it is not already opened :
var wb = Marshal.BindToMoniker(#"C:\x.xlsx") as Microsoft.Office.Interop.Excel.Workbook;
https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/
Old answer :
GetObject can be used with reference to Microsoft.VisualBasic (it also opens the file if needed) :
object o = Microsoft.VisualBasic.Interaction.GetObject(#"C:\x.xlsx", "Excel.Application");
var wb = o as Microsoft.Office.Interop.Excel.Workbook;
if (wb != null)
{
Microsoft.Office.Interop.Excel.Application xlApp = wb.Application;
// your code
}
Reference to Microsoft.VisualBasic can probably be avoided by checking the GetObject source code https://github.com/Microsoft/referencesource/blob/master/Microsoft.VisualBasic/runtime/msvbalib/Interaction.vb#L1039
This seems to be C# version
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = null;
try
{
excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
}
catch (COMException exc)
{
// ....
}
obviously assuming that the file is opened by an excel application on the same machine.
But the point is that Marshal.GetActiveObject will always return the first instance it finds on ROT (running object table). This is because Office doesn't register new objects. You have to get the application from the child windows, like suggested in this more complicated answer.
Try it this way.
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
From here:
How to write some data to excel file(.xlsx)
Also, check this out.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
I'm trying to create a excel from a datagrid with wpf, however when I format a column to just text it still converts some columns to what I presume to be a date conversion.
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
This is how the conversion of the column is set, but this results in Excel still formatting some fields to a date-ish value... If you look at the column foutcode you'll see what I mean.
results in:
I think what happens is that it automatically recognizes the value and sees if it fits a date format while I'm telling it to handle as just regular text! So does anyone have any idea on how to get rid of that? because the data is unusable because of this small error. Maybe use a more specific format than just text? however I can't seem to figure out how.
Also Convert a lot of rows into excel takes some quite a bit of time (4-5s for 1000 rows). Is there a way to make it go faster? All help is really appreciated.
public void ExportToExcel(List<Fouten> data)
{
try
{
if (data.Count > 0)
{
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = "Data rapport";
// If the User Clicks the Save Button then the Module gets executed otherwise it skips the scope
if ((bool)saveFileDialog1.ShowDialog())
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rowCount = 1;
xlWorkSheet.Cells[rowCount, 1] = "Datum";
xlWorkSheet.Cells[rowCount, 2] = "Tijd";
xlWorkSheet.Cells[rowCount, 3] = "Foutcode";
xlWorkSheet.Cells[rowCount, 4] = "Omschrijving";
xlWorkSheet.Cells[rowCount, 5] = "Module";
xlWorkSheet.Cells[rowCount, 6] = "TreinId";
rowCount++;
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 2];
rg.EntireColumn.NumberFormat = "hh:mm:ss.000";
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
foreach (Fouten item in data)
{
string[] moduleNaam = item.Module.Split('_');
xlWorkSheet.Cells[rowCount, 1] = item.Datum;
xlWorkSheet.Cells[rowCount, 2] = item.Time.ToString();
xlWorkSheet.Cells[rowCount, 3] = item.FoutCode;
xlWorkSheet.Cells[rowCount, 4] = item.Omschrijving;
xlWorkSheet.Cells[rowCount, 5] = moduleNaam[0].ToUpper();
xlWorkSheet.Cells[rowCount, 6] = item.TreinId;
rowCount++;
}
xlWorkSheet.Columns.AutoFit();
// If the file name is not an empty string open it for saving.
if (!String.IsNullOrEmpty(saveFileDialog1.FileName.ToString()) && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName.ToString()))
{
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel File Exported Successfully", "Export Engine");
}
}
}
}
else
{
MessageBox.Show("Nothing to Export", "Export Engine");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The Range.NumberFormat property for Text is an 'at' symbol (e.g. capital 2 or #), not the word Text.
rg1.EntireColumn.NumberFormat = "#";
More at Number Format Codes.
I have a datatable and want it to export it to excel file, it is a wpf application and all the solutions that i have found are for web application asp.net please help...
just to make it better visible, for all
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
Microsoft.Office.Interop.Excel.Range rng = null;
try
{
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Add();
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
for (int Idx = 0; Idx < dt.Columns.Count; Idx++)
{
ws.Range["A1"].Offset[0, Idx].Value = dt.Columns[Idx].ColumnName;
}
for (int Idx = 0; Idx < dt.Rows.Count; Idx++)
{ // <small>hey! I did not invent this line of code,
// I found it somewhere on CodeProject.</small>
// <small>It works to add the whole row at once, pretty cool huh?</small>
ws.Range["A2"].Offset[Idx].Resize[1, dt.Columns.Count].Value =
dt.Rows[Idx].ItemArray;
}
excel.Visible = true;
wb.Activate();
}
catch (COMException ex)
{
MessageBox.Show("Error accessing Excel: " + ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
You can save a .csv(Comma Seperated Value File) from your datatable. This file can then be opened in Excel.
Moreover: Whether it is WPF or Winforms, converting is same in both because its conversion code is written in your language i.e. C# and is not specific to WPF or Winforms.
For me Work fine thank you ... some one like vb.net ?
Dim excel As Microsoft.Office.Interop.Excel.Application = Nothing
Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim missing As Object = Type.Missing
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim rng As Microsoft.Office.Interop.Excel.Range = Nothing
Sub ExcelFile(ByVal dt As DataTable)
Try
excel = New Microsoft.Office.Interop.Excel.Application()
wb = excel.Workbooks.Add()
ws = DirectCast(wb.ActiveSheet, Microsoft.Office.Interop.Excel.Worksheet)
For Idx As Integer = 0 To dt.Columns.Count - 1
ws.Range("A1").Offset(0, Idx).Value = dt.Columns(Idx).ColumnName
Next
For Idx As Integer = 0 To dt.Rows.Count - 1
' <small>hey! I did not invent this line of code,
' I found it somewhere on CodeProject.</small>
' <small>It works to add the whole row at once, pretty cool huh?</small>
' YES IT'S COOL Brother ...
ws.Range("A2").Offset(Idx).Resize(1, dt.Columns.Count).Value = dt.Rows(Idx).ItemArray
Next
excel.Visible = True
wb.Activate()
Catch ex As Exception
MessageBox.Show("Error accessing Excel: " & ex.ToString())
End Try
End Sub
one way
ArrayList arr = (ArrayList)dataGridView.DataSource;
dt = ArrayListToDataTable(arr);
dataTable2Excel(dt, dataGridView, pFullPath_toExport, nameSheet);
http://www.codeproject.com/Articles/30169/Excel-export-from-DatagridView
http://support.microsoft.com/default.aspx?scid=kb;en-us;317719
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();