使用Winform上的对话框将数据网格导出到Excel

时间:2013-10-31 15:28:47

标签: c# winforms excel datagrid export-to-excel

我正在寻找如何使用在特定位置保存数据的对话框将数据网格(或数据集)(而非数据网格视图)导出到Excel,我正在使用VS 2003 Winform而不是Webform。

这是我的代码:

我只需要打开一个对话框让用户选择他想要放置文件的位置:

private void button2_Click(object sender, System.EventArgs e)
        {
#region
                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);

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

                xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);

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

我还有另一个代码:

#region
////            lblMessage.Visible = true;
////            lblMessage.Text = "";
//          // Export all the details
//          try
//          {           
//              // Get the datatable to export          
//              DataTable dt = dsSelectionListeDiffere.Tables[0].Copy();
//              dsSelectionListeDiffere = FrmFonctionPrincipale.getListeDifferesParClient(1);
//              // Export all the details to Excel
//
//
//              RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win");             
//              objExport.ExportDetails(dt, Export.ExportFormat.Excel, "C:\\EmployeesInfo.xls");
//              MessageBox.Show("Exporté Avec Succès dans  C:\\EmployeesInfo.xls");
//          }
//          catch(Exception Ex)
//          {
//              MessageBox.Show(Ex.Message);
////                lblMessage.Text = Ex.Message;
//          }
        #endregion

1 个答案:

答案 0 :(得分:0)

如果您不需要更改文件名,只需更改保存此文件的文件夹,则可以使用FolderBrowserDialog仅询问保存文件的文件夹

private void button2_Click(object sender, System.EventArgs e)
{
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.Description = "Select the destination folder";
    fbd.ShowNewFolderButton = true;
    fbd.RootFolder = Environment.SpecialFolder.Personal;
    if( fbd.ShowDialog() == DialogResult.OK )
    {
        string folderName = fbd.SelectedPath;
        .... the rest of your excel export code .....

        // Pass the full path to the SaveAs method
        string fullPathName = Path.Combine(folderName, "csharp.net-informations.xls");
        xlWorkBook.SaveAs(fullPathName, .....);

        .....

        MessageBox.Show("Excel file created , you can find the file in: " + fullPathName);
   }

如果您还需要更改文件名,则需要使用SaveFileDialog实例。

 SaveFileDialog sfd = new SaveFileDialog();
 sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*"  ;
 sfd.FilterIndex = 1 ;
 sfd.RestoreDirectory = true ;
 sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
 if(sfd.ShowDialog() == DialogResult.OK)
 {
     if(sfd.FileName.Length > 0)
     {
        ... the rest of your excel code here ....

        // sfd.FileName already contains the full path so
        xlWorkBook.SaveAs(sfd.FileName, .....);

     }
 }
 else
 {
      if(MessageBox.Show("Are you sure you want to quit without saving?", "Quitting",
                         MessageBoxButtons.YesNo) == DialogResult.No)
      {
          // This important to stop the Form to close if this button is the Cancel/AcceptButton
          // or its property DialogResult is not DialogResult.None
          this.DialogResult = DialogResult.None;
      }
 }