0

How can I specify which sheet I want to write to by name? For example, I want to specify that the sheet I should be modifying should be labeled "212".

Also, perhaps a more challenging question. How can I ensure that the sheets I create are always in alphabetical order? Is that a property I can set through excel maybe?

1
Contributor
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Duki
0

Figured it out - here's an excerpt from my code:

class ExcelWriter
{
private object oMissing = System.Reflection.Missing.Value;
private Excel.Application xl = new Excel.Application();
private Excel.Workbook xlBook;
private Excel.Worksheet xlSheet;

private string file_path = "C:\\Users\\ctote.REG\\Documents\\";

public void CreateSheet(string file, string sheet)
{
     try
     {
         xlBook = xl.Workbooks.Open(file_path + file, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
         xlSheet = xlBook.Worksheets.get_Item(2);
               
         int last = xlBook.Worksheets.Count;
         xlSheet.Copy(oMissing, xl.Worksheets[last]);
         xl.Worksheets[last+1].name = sheet;

         xlBook.Save();
    }
    catch (Exception ex)
    {
         MessageBox.Show("Create Error:  " + ex.Message, "Could not create sheet", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
         xl.Application.Workbooks.Close();
         xl.Workbooks.Close();
         xl.Quit();
         System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
         System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
         System.Runtime.InteropServices.Marshal.ReleaseComObject(xl);
     }
}
...
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.