2
Reply

Problem in creating and saving Excel file using C#. Plz help!!!

kedar joshi

kedar joshi

Feb 5 2008 1:08 AM
10.9k

HEllo guys,
i am using listview control in C#.
I need to create Excel file runtime and want to save all Listview content into it.
I have done some coding but i could found only
"theWorkbook = ExcelObj.Workbooks._Open(...)" method.
I couldn't find any method to create file.
I am also facing some problem in saving and closing file as the file is getting opened in 'Read Only' type.
Excel object remains undestroyed even after application close.


Code that i have written is as follows.

private void saveLog_btn_Click(object sender, EventArgs e)
    {
      Microsoft.Office.Interop.Excel.Workbook theWorkbook;
      Microsoft.Office.Interop.Excel.Worksheet worksheet;
      Microsoft.Office.Interop.Excel.Application ExcelObj = null;
     
      string strMessage = "File created at " + m_PathOfLog;
      try
      {
        ExcelObj= new Microsoft.Office.Interop.Excel.Application();
        theWorkbook = ExcelObj.Workbooks._Open(m_PathOfLog, 0, false, 5,
        "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, true, 0, true);
       
 Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;

        worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);

        int i = 1;
        foreach (ListViewItem currItem in lstViewResult.Items)
        {
            worksheet.Cells[i, 1] = i;
            worksheet.Cells[i, 2] = currItem.SubItems[0].Text;
            if (currItem.SubItems.Count <= 1)
            {
              worksheet.Cells[i, 3] = "";
            }
            else
            {
              worksheet.Cells[i, 3] = currItem.SubItems[1].Text;
            }
            i = i + 1;
        }
        ExcelObj.Save(m_PathOfLog);
        ExcelObj.Workbooks.Close();
        theWorkbook.Close((System.Boolean)false, m_PathOfLog, System.Type.Missing);
        ExcelObj.Quit();
}

I request you to help me to find solution to this problem.

Regards,
Kedar


Answers (2)