properly closing Microsoft.Office.Interop.Excel within c# thread - c#

I've made an application that logs data to an excel file.
I can't open the excel file until I've closed the application.
In task manager excel.exe is still running after I've closed the excel application in code.
I've tried at least 11 ways of closing excel but it doesn't work.
All the code is executed from a thread:
thread = new Thread(() => export_parameters(path));
public class xlsx_logfile
{
private Microsoft.Office.Interop.Excel._Application excel;//excel application that is used for creating excel workbooks(files)
private Microsoft.Office.Interop.Excel.Workbooks workbooks;
private Microsoft.Office.Interop.Excel._Workbook workbook;//excel workbook(file)
private Microsoft.Office.Interop.Excel._Worksheet worksheet;
private string filename;
public xlsx_logfile(string path)
{
//destructor?
excel = new Microsoft.Office.Interop.Excel.Application();
workbooks = excel.Workbooks;
workbook = workbooks.Add(Type.Missing);
worksheet = null;
worksheet = workbook.ActiveSheet;
worksheet.Name = "sensordata";
filename = path;
}
public void column_add(uint column_zerobased_index,string header, string format, double[] data)
{
Microsoft.Office.Interop.Excel.Range formatRange;
Microsoft.Office.Interop.Excel.Range c1;
//Microsoft.Office.Interop.Excel.Range c2;
column_zerobased_index = 0;
//var worksheet = workbook.ActiveSheet;
c1 = worksheet.Cells[1, column_zerobased_index+1];
//c2 = oSheet.Cells[4, 4];
formatRange = worksheet.get_Range(c1,c1);//column_zerobased_index + 1
formatRange.EntireColumn.NumberFormat = "0.0";
worksheet.Cells[1, column_zerobased_index+1].NumberFormat = "#";
worksheet.Cells[1, column_zerobased_index + 1] = header;
//todo use: https://stackoverflow.com/questions/3989122/microsoft-office-interop-excel-really-slow
for (int i = 0; i < data.Length; ++i)
{
worksheet.Cells[i + 1 + 1, column_zerobased_index+1] = data[i];
}
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.ReleaseComObject(formatRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(c1);
}
void close(string filename)
{
//worksheet = null;
//workbook.Close();
//workbook = null;
//excel = null;
//excel.Quit();
//worksheet = null;
//workbook = null;
//excel = null;
//worksheet = null;
//workbook.Close();
//workbook = null;
//excel.Quit();
//excel = null;
//worksheet = null;
//workbook.Close();
//workbook = null;
//var workbooks_local = excel.Workbooks;
//var workbook_local = workbooks_local.Open(filename);
//workbook_local.Close();
//workbooks_local.Close();
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook_local);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks_local);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
//worksheet = null;
////workbook.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//workbook = null;
////excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//excel = null;
////based on https://stackoverflow.com/questions/1526685/c-how-can-i-open-and-close-an-excel-workbook
//workbook.Close(false, filename, null);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//workbook = null;
//excel = null;
//GC.Collect();
//GC.WaitForPendingFinalizers();
//GC.Collect();
//GC.WaitForPendingFinalizers();
//var aap = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
//System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
//worksheet = null;
//workbook.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//workbook = null;
//workbooks.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
//workbooks = null;
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//excel = null;
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlRng);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(worksheet);
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
excel.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);
}
public void save()
{
workbook.SaveAs(filename);
close(filename);
}
}
edit: this question is different from Closing Excel Application Process in C# after Data Access because I'm executing from a thread, not a method. The provided answers didn't work.
I solved the problem myself:
private Microsoft.Office.Interop.Excel._Application excel;//excel application that is used for creating excel workbooks(files)
private Microsoft.Office.Interop.Excel._Workbook workbook;//excel workbook(file)
private Microsoft.Office.Interop.Excel._Worksheet worksheet;
excel = new Microsoft.Office.Interop.Excel.Application();
workbook = excel.Workbooks.Add();
worksheet = workbook.ActiveSheet;
workbook.Close();
excel.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);
worksheet = null;
workbook = null;
excel = null;

Related

Get Excel Active Worksheet with C#

I am wondering why this code gets the open worksheet when I run it in debug, and catch an exception when I run it with no debug..
Excel.Application xlApp = null;
Excel.Workbook xlWBook = null;
Excel.Worksheet xlWSheet = null;
Excel.Range xlRange = null;
try {
xlApp = (Excel.Application) Marshal.GetActiveObject("Excel.Application");
xlApp.Visible = true;
xlWBook = xlApp.ActiveWorkbook;
xlWSheet = xlWBook.ActiveSheet;
xlRange = xlWSheet.UsedRange;
logResult = logResult + "Agganciato " + xlWBook.Name + " \r\n";
} catch {
logResult = logResult + "Nessun file aperto rilevato. \r\n";
}
Any suggestion?
The following shows how one can use Excel Interop to either interact with an open Excel workbook or create a new workbook if one isn't open.
Try the following:
Add Reference (Option 1)
Download / install NuGet package: Microsoft.Office.Interop.Excel
Add Reference (Option 2)
In VS menu, click Project
Select Add Reference...
Click COM
Check Microsoft Excel xx.x Object Library (ex: Microsoft Excel 16.0 Object Library)
Add the following using directives:
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
CreateExcelWorkbook
public void CreateExcelWorkbook(string filename)
{
bool isExcelAlreadyRunning = false;
string logResult = string.Empty;
Excel.Application xlApp = null;
Excel.Workbook xlWBook = null;
Excel.Worksheet xlWSheet = null;
Excel.Range xlRange = null;
try
{
try
{
//if Excel isn't open, this will throw a COMException
xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
//set value
isExcelAlreadyRunning = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
//create new instance
xlApp = new Excel.Application();
}
//whether or not to make Excel visible
xlApp.Visible = true;
//prevent prompting to overwrite existing file
xlApp.DisplayAlerts = false;
//disable user control while modifying the Excel Workbook
//to prevent user interference
//only necessary if Excel application Visibility property = true
//need to re-enable before exitin this method
//xlApp.UserControl = false;
if (xlApp.Workbooks.Count > 0)
xlWBook = xlApp.ActiveWorkbook;
else
xlWBook = xlApp.Workbooks.Add();
if (xlWBook.Worksheets.Count > 0)
xlWSheet = xlWBook.ActiveSheet;
else
xlWSheet = xlWBook.Sheets.Add();
xlRange = xlWSheet.UsedRange;
//set value
xlWSheet.Cells[1, 1] = $"Test {DateTime.Now.ToString("HH:mm:ss.fff")}";
//save Workbook - if file exists, overwrite it
// xlWBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookDefault, System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
xlWBook.SaveAs(filename, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
logResult = logResult + "Agganciato " + xlWBook.Name + " \r\n";
}
catch
{
logResult = logResult + "Nessun file aperto rilevato. \r\n";
}
finally
{
if (xlWBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWSheet);
xlWSheet = null;
xlRange = null;
if (!isExcelAlreadyRunning)
{
//close workbook
xlWBook.Close(false);
}
//release all resources
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWBook);
xlWBook = null;
}
System.Threading.Thread.Sleep(150);
if (xlApp != null)
{
if (!isExcelAlreadyRunning)
{
xlApp.Quit();
}
//release all resources
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(175);
}
}
}
Usage:
CreateExcelWorkbook(filename);
//the following is necessary otherwise the Excel process seems to persist in Task Manager
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Resources:
Microsoft.Office.Interop.Excel Namespace
Excel is still running though I quit and released the object
Cannot close Excel.exe after Interop process

C# Excel process won't close

I'm writing a program where you can enter stuff into an excel via a button.
When the button is pressed the Application is started it interacts with the spreadsheet.
But when it's finished interacting the process should be closed completely but it hangs in the Task Manager.
I've tried numerous solutions to close it but it won't.
Here is my code
using Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Runtime.InteropServices;
using Application = Microsoft.Office.Interop.Excel.Application;
.
.
.
.
Application oxl = null;
Workbooks wbs = null;
Workbook wb = null;
Worksheet ws = null;
Sheets wss = null;
Range r = null;
Range orange2 = null;
Range resultRange = null;
try {
oxl = new Application();
wbs = oxl.Workbooks;
wb = wbs.Open(Settings.Default.excelPath);
wss = wb.Worksheets;
ws = (Worksheet) wss[2];
r = ws.Range["A2:A924"];
foreach(string tofind in tofinds) {
resultRange = null;
string[] s = data[tofind];
resultRange = r.Find(
What: tofind,
LookIn: XlFindLookIn.xlValues,
LookAt: XlLookAt.xlPart,
SearchOrder: XlSearchOrder.xlByRows,
SearchDirection: XlSearchDirection.xlPrevious,
MatchCase: true);
if (resultRange != null) {
int i = resultRange.Row;
orange2 = ws.Cells[i, 2];
if (orange2.Value == null) {
orange2 = ws.Cells[i, 2];
//s[0]= -3.94e6
orange2.Value = s[0].Split((char)
'e')[0].Replace("-", "");
orange2.NumberFormat = "0.00";
}
} else {
//Log to Console
}
}
wb.Save();
} catch (IOException e) {
Console.WriteLine(e.Message);
} finally {
Marshal.FinalReleaseComObject(orange2);
Marshal.FinalReleaseComObject(r);
Marshal.FinalReleaseComObject(resultRange);
orange2 = null;
r = null;
resultRange = null;
foreach(Worksheet sheet in wss) {
Marshal.FinalReleaseComObject(sheet);
}
Marshal.FinalReleaseComObject(wss);
wss = null;
wb.Close(0);
wbs.Close();
foreach(Workbook workbook in wbs) {
Marshal.FinalReleaseComObject(workbook);
}
Marshal.FinalReleaseComObject(wb);
wb = null;
Marshal.FinalReleaseComObject(wbs);
wbs = null;
oxl.Application.Quit();
oxl.Quit();
Marshal.FinalReleaseComObject(oxl);
oxl = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Final");
}
Found the Solution.
If you get your Range by
Range r = sheet.Cells[1,1];
Marshal.FinalReleaseComObject(r);
r = null;
Cells[1,1] creates an own COM object
Rang r1 = sheet.Cells;
Range r = r1[1,1];
Marshal.FinalReleaseComObject(r1);
r1 = null;
Marshal.FinalReleaseComObject(r1);
r1 = null;
by doing that it worked for me

Will this work if I change the active sheets throughout my code?

I am running a script to format sheets in an existing excel file. Here is what I have now:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmm");
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::DestinationFilePath1"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
It doesn't do anything at the moment, just opens the workbook and sets the active worksheet. There are 3 different sheets in the workbook that I need to format, so would I be able to do this like so?:
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[2];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[3];
sheet.Select(Type.Missing);
//do work here
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}

C# Excel Write to multiple cells

Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, 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 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, 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();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.

Error while generating excel from C#

I have simple code for generating Excel which loops and produces excel sheet.
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value,Missing.Value,
6, Missing.Value);
for (int j = 0; j < 7; j++)
{
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName.ToString();//Sheetname has a Name
}
Now the problem is When we run this code everything works fine. But sometimes what happens is, at the client side one of the sheet name is not generated it skips. So our solution to them is to try generating the sheet again and then it works fine,
So my question is why does the code skip the sheetName (sometimes), although there is no problem in the code. Does it have to do anything with clients other running processes?
Try this:
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
// here you get the first ws, index 1
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value, Missing.Value,
6, Missing.Value);
var SheetName = "sheet_";
// here you should start from 1 (not from 0) and include 7 in the loop count
for (int j = 1; j <= 7; j++)
{
// make sure that the ws name is unique
SheetName=String.Format("sheet_{0}",j);
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName;// this is already a string
}
XlApp.Quit();

Categories

Resources