Hi,

I want to save datagridview data in Excel sheet as per user spcify the location for that I write some code but It's not working properly. If I spacify the location in the code then It alway overwite the data on previous data. In Savedialog Box when I spcify the location It create a Excel File but can not open. Other wise It Save that file and again show the savedialogbox with the name of Book.

SqlConnection cnn;
            string connectionString = null;
            string sql = null;
            string data = null;
            int i = 0;
            int j = 0;

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\cement.mdf;Integrated Security=True;User Instance=True";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = "SELECT * FROM stcaccshu";
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet ds = new DataSet();
            dscmd.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                    xlWorkSheet.Cells[i + 1, j + 1] = data;
                }
            }


            Stream myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {

                    StreamWriter wText = new StreamWriter(myStream);
                   xlWorkBook.SaveAs("abc",Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                }
            }

[B]When I spacify The Location In Code

                     xlWorkBook.SaveAs("@ d:\\praj.SAI", Excel.XlFileFormat.xlWorkbookNormal,misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);[/B]
               
                    xlApp.Quit();

                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
             
                    MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
              
        }

Dani AI

Generated

Short answer for and : the corrupt/ unreadable file is almost always caused by the way the file is being created and locked before Excel writes to it, or by a mismatch between the filename extension and the Workbook save format. The common pattern that breaks things is opening a file stream from the Save dialog and then asking the Excel interop to save to a different target (or to the same path while the stream is still open).

Fix checklist (in order)

  • Do not use the dialog's open stream. Use the dialog FileName property and pass that full path to the Excel save operation. The dialog OpenFile() creates and holds an open stream that can lock or truncate the file; see the SaveFileDialog.OpenFile documentation for details (OpenFile docs).
  • Make the file extension and the Excel save format match (for example, use the older .xls format for Excel 97–2003 file types and the OpenXML format for .xlsx). A mismatch often produces "file cannot be read" errors — see the workbook SaveAs reference ().
  • Close and quit Excel objects, then release COM references in reverse order. Call Marshal.ReleaseComObject on worksheet/workbook/application, set variables to null, and force GC to avoid leftover locked excel.exe processes ().

Extra notes

  • If Excel is not installed or this runs on a server, use a library that writes XLS/XLSX directly (EPPlus, ClosedXML or NPOI) rather than Interop.
  • For troubleshooting: try saving to a simple local folder with a clearly matching extension, avoid opening the dialog stream, confirm no lingering Excel processes, and check for exceptions during SaveAs.

Please Help Me...

The Excel file is convert properly but I have problem in SaveDialogBox It not save properly. It display error message "File can not be read".

I use very similar code and have same problem. Whats wrong?

Thx for help to all. R.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.