DevExpress学习之GridControl导入导出至EXCEL

导出:

   

private void EXCELout_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "导出Excel";
saveFileDialog.Filter = "Excel文件(*.xls)|*.xls";
DialogResult dialogResult = saveFileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
gridControl1.ExportToXls(saveFileDialog.FileName, options);
// gridControl1.ExportToExcelOld(saveFileDialog.FileName);
DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

导入:

private void EXCELIN_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Excel文件";
ofd.FileName = "";
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
ofd.Filter = "所有文件(*.*)|*.*|Excel2003文件(*.xls)|*.xls|Excel2007文件(*.xlsx)|*.xlsx";
ofd.ValidateNames = true;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
string strName = string.Empty;
if (ofd.ShowDialog() == DialogResult.OK)
{
strName = ofd.FileName;
}
if (strName == "")
{
XtraMessageBox.Show("没有选择Excel文件!无法进行数据导入");
return;
}
else
{
try
{
DataSet myDs = new DataSet();
string text = string.Format("Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '{0}';Extended Properties=Excel 8.0", strName);
string excelFirstTableName = GetExcelFirstTableName(text);
myDs.Tables.Clear();
myDs.Clear();
this.gridControl1.DataSource = null;
OleDbConnection selectConnection = new OleDbConnection(text);
OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(string.Format("select * from [{0}]", excelFirstTableName), selectConnection);
oleDbDataAdapter.Fill(myDs);
this.gridControl1.DataSource = myDs.Tables[0];
this.GV.PopulateColumns();
}
catch (Exception ex)
{
XtraMessageBox.Show("从电子表格文件中装载数据异常!", ex.Message);
}
}
}

posted on 2022-11-10 09:58  林좋아해요  阅读(369)  评论(0)    收藏  举报