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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix