我正在寻找如何使用将数据保存在特定位置的对话框将数据网格(或数据集)(不是数据网格视图)导出到 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