Home » excel » excel – excell in C# – got problem with 2 sheet

excel – excell in C# – got problem with 2 sheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

i use this code for making excell from dataset:

SQL = "select Bar,Store,Serial from Counter";
            dsView = new DataSet();
            adp = new OleDbDataAdapter(SQL, Conn);
            adp.Fill(dsView, "Counter");
            adp.Dispose();
 Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
        xla.Visible = false  ; 
        Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)xla.ActiveSheet;
        int i = 1;
        foreach (DataRow comp in dsView.Tables[0].Rows)
        {
            ws.Cells[i, 1] = comp[0].ToString();
            ws.Cells[i, 2] = comp[1].ToString();
            ws.Cells[i, 3] = comp[2].ToString();
            i++;
        }

and i have 2 problem

how to open new sheet and how to close this process

(i see that the Excell allwais runs on background)

How to&Answers:

How to open new sheet?

You may add a new sheet by using the Workbook.Worksheets.Add method.

var newWorksheet = 
    (Worksheet)xla.Worksheets.Add(Type.Missing
                                , Type.Missing
                                , Type.Missing
                                , Type.Missing);

How to close this process?

You have to close the workbooks and dispose of the application instance.

SQL = "select Bar,Store,Serial from Counter";
dsView = new DataSet();
using (adp = new OleDbDataAdapter(SQL, Conn)) 
    using (Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application()) {
        adp.Fill(dsView, "Counter");

        xla.Visible = false  ; 

        try {
            Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
            Worksheet ws = (Worksheet)xla.ActiveSheet;

            int i = 1;

            foreach (DataRow comp in dsView.Tables[0].Rows) {
                ws.Cells[i, 1] = comp[0].ToString();
                ws.Cells[i, 2] = comp[1].ToString();
                ws.Cells[i, 3] = comp[2].ToString();
                i++;
            }
        } finally {
            // Notice that the two following lines are totally optional as the use of 
            // using blocks assure that the used resource will necessarily be disposed
            // when getting out of the using blocks scope.
            adp.Dispose();
            xla.Dispose();
        }
}

Here a few links for getting acquainted to working with the Microsoft.Office.Interop.Excel COM assembly.

  1. How to: Add New Worksheets to Workbooks;
  2. Working with Worksheets;
  3. Working with Workbooks;
  4. Working with Ranges;
  5. Working with Cells.