简体   繁体   中英

Excel not opening generated from c#

I am trying to store Datatable in excel which is generated in c# (SSIS ScriptTask).

Below is my code:

        OleDbDataAdapter A = new OleDbDataAdapter();
        System.Data.DataTable dt = new System.Data.DataTable();
        A.Fill(dt, Dts.Variables["User::ObjResultSet"].Value);


         Excel.Application oXL = new Excel.ApplicationClass();
        Excel.Workbooks oWBs = oXL.Workbooks;
        Excel.Workbook oWB = null;
        Excel.Worksheet oSheet;

        oWB = oWBs.Count > 0 ? oWB = oWBs[0] : oWBs.Add(System.Reflection.Missing.Value);



        oXL.DisplayAlerts = false;

        oWB = oXL.Workbooks.Add(Missing.Value);

        oSheet = (Excel.Worksheet)oWB.Worksheets[1];

        int rowCount = 1;
        foreach (DataRow dr in dt.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < dt.Columns.Count + 1; i++)
            {
                // Add the header time first only
                if (rowCount == 2)
                {
                    oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                }
                oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        oWB.SaveAs(Dts.Variables["User::ExcelPath"].Value, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlExclusive,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        oWB.Close(false, Dts.Variables["User::ExcelPath"].Value, Missing.Value);
        oWBs.Close();
        oXL.Quit();


        Dts.TaskResult = (int)ScriptResults.Success;

What problem I am facing is, excel is generated. But When I try to generate .xls , It works completely fine. But this doesn't work when I try to generate .xlsx .

Can anyone help me?

Try using Excel.XlFileFormat.xlOpenXMLWorkbook instead of Excel.XlFileFormat.xlWorkbookNormal

[Updated]

oWB.SaveAs(Dts.Variables["User::ExcelPath"].Value, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);

Warning - it's a pure C# attempt without that SSIS. Here's an approach I used a while back, so it probably is without any good practice in it at all. Others should if possible refine it, if they see it. This was used to have a DataTable with 2 columns. 1 for the TimeStamp and 1 for a value. So you have to fit it in as you need it.

private void createXLSXFromDataTable(System.Data.DataTable table, string path)
        {
            MemoryStream ms = new MemoryStream();
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("data");
                worksheet.Cells["A1"].LoadFromDataTable(table,true);
                worksheet.Column(1).Style.Numberformat.Format = "dd/mm/yyyy\\ hh:mm";
                worksheet.Column(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                byte[] excelData = package.GetAsByteArray();
                ms.Write(excelData, 0, excelData.Length);
            }
            ms.Flush();
            using (FileStream fs = File.Create(pfad))
            {
                ms.WriteTo(fs);
            }
            //open again with ms office, 
            //so the file will get saved correctly and
            //all columns have the correct format
            Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
            application.Visible = false;
            Workbooks wbooks = application.Workbooks;
            wbooks.Open(pfad, Origin: XlPlatform.xlWindows);
            Workbook wbook = application.ActiveWorkbook;
            wbook.Save();
            //quitting the services,
            //after that delete/stop COM-connections of each object
            wbook.Close();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wbook);
            wbooks.Close();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wbooks);
            application.Quit();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(application);
            MessageBox.Show("Document successfully created.");
        }

It could be, that you have to open the excel file again and save it in your code. At least that error happened to me back in the time when I created my posted code, so that's why I opened the file again in the code and saved it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM