DevExpress XtraGrid 数据导出导入Excel

// <summary>
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmAppItem_F9ClickHandler(object sender, EventArgs e)
        {
            string strName = "";
            try
            {
                if (gvSelectedItems.RowCount == 0)
                {
                    MessageBoxShow.ShowProMessage("Grid表格中没有数据,不能导出为Excel");
                    return;
                }
                DateTime MMSDate = RealSailing.UI.Service.ServiceManager.GetSystemDateTime();
                using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                {
                    saveFileDialog.Filter = "导出Excel(*.xls)|*.xls";
                    saveFileDialog.FilterIndex = 0;
                    saveFileDialog.RestoreDirectory = true;
                    saveFileDialog.CreatePrompt = true;
                    saveFileDialog.Title = "导出文件保存路径";
                    //默认的文件名
                    saveFileDialog.FileName = strTitle + " - " + MMSDate.ToString("yyyyMMdd");
                    //saveFileDialog.ShowDialog();
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        strName = saveFileDialog.FileName;
                        if (strName.Length != 0)
                        {
                            gridColumn2.Visible = false;
                            gridItemID2.Visible = true;
                            gridItemID2.VisibleIndex = 0;
                            gvSelectedItems.ExportToXls(strName);
                            gridColumn2.Visible = true;
                            gridItemID2.Visible = false;
                            MessageBoxShow.ShowProMessage("导出Excel成功", strTitle);
                            //关闭操作
                            System.Reflection.Missing miss = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application();
                            Microsoft.Office.Interop.Excel.Workbook objWorkBook = objExcel.Workbooks.Add(miss);
                            Microsoft.Office.Interop.Excel.Worksheet objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkBook.ActiveSheet;
                            objWorkBook.Close(null, null, null);
                            objExcel.Workbooks.Close();
                            objExcel.Quit();
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkBook);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet);
                            objSheet = null;
                            objWorkBook = null;
                            objExcel = null;
                        }
                        else
                        {
                            MessageBoxShow.ShowProMessage("保存的Excel名称不能为空");
                        }

                    }
                }
            }
            catch (System.Exception msg)
            {
                MessageBoxShow.ShowProMessage(msg.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

导入Excel
      /// <summary>
        /// 导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmAppItem_F8ClickHandler(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Excel文件";
                ofd.FileName = "";
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                ofd.Filter = "Excel文件(*.xls)|*.xls";
                ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
                ofd.CheckFileExists = true; //验证路径有效性
                ofd.CheckPathExists = true; //验证文件有效性
                string strName = string.Empty;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    strName = ofd.FileName;
                }
                if (strName == "")
                {
                    return;
                }
                if (EcxelToGridView(strName, this.gvSelectedItems))
                {
                    MessageBoxShow.ShowProMessage("数据导入成功", strTitle);
                    //isChanged = true;
                }
                else
                    MessageBoxShow.ShowProMessage("数据导入失败,请检查导入的Excel格式与数据是否正确", strTitle);
                this.Cursor = Cursors.Default;
            }
            catch (System.Exception Msg)
            {
                MessageBoxShow.ShowProMessage("数据导入失败,请检查导入的Excel格式与数据是否正确", strTitle);
                //MessageBoxShow.ShowErrMessage(Msg.ToString()+"数据导入失败,请检查导入的Excel格式与数据是否正确");
            }
        }
        /// <summary>
        /// Excel数据导入方法
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public bool EcxelToGridView(string filePath, DevExpress.XtraGrid.Views.Grid.GridView dgv)
        {
            bool isVailed = false;
            string itemid = string.Empty;
            string itemplu = string.Empty;
            string itemName = string.Empty;
            //根据路径打开一个Excel文件并将数据填充到ds中
            try
            {
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties =‘Excel 8.0;HDR=YES;IMEX=1‘";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                //获取Excel中的sheet的名称
                string SheetName= GetExcelSheetNames(filePath)[0];
                //strExcel = "select * from [sheet1$]";
                strExcel = "select * from [" + SheetName + "$]";
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                // RealSailing.DataSet.SlipInfo.SLPD010_SLIPSUMHDS ds = new RealSailing.DataSet.SlipInfo.SLPD010_SLIPSUMHDS();
                System.Data.DataSet ds = new System.Data.DataSet();
                myCommand.Fill(ds, "table1");
                conn.Close();
                if (ds.Tables["table1"].Rows.Count == 0)
                {
                    MessageBoxShow.ShowProMessage("要导入的Excel没有数据");
                }
                ExcelDS.Clear();
                for (int j = 0; j < ds.Tables["table1"].Rows.Count; j++)
                {
                    if (ds.Tables["table1"].Rows[j]["商品id"].ToString().Trim() != string.Empty)
                        itemid = ds.Tables["table1"].Rows[j]["商品id"].ToString().Trim();
                    if (ds.Tables["table1"].Rows[j]["商品货号"].ToString().Trim() != string.Empty)
                        itemplu = ds.Tables["table1"].Rows[j]["商品货号"].ToString().Trim();
                    else
                        itemplu = " ";
                    if (ds.Tables["table1"].Rows[j]["商品名称"].ToString().Trim() != string.Empty)
                        itemName = ds.Tables["table1"].Rows[j]["商品名称"].ToString().Trim();
                    //把数据填充到ds中
                    FillDataToDs(itemid, itemplu, itemName);
                    isVailed = true;
                }
                if (lblSelectDs.Tables["MSTM150_ITEM"].Rows.Count == 0)
                {
                    isVailed = false;
                }
                else if (ExcelDS.Tables["MSTM150_ITEM"].Rows.Count>0)
                {//重复数据 显示提示
                    MsShowData msShow = new MsShowData();
                    msShow.GetDs = ExcelDS;
                    msShow.ShowDialog();
                    isVailed = true;
                }
                return isVailed;
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                if (ex.Message.IndexOf("不是一个有效名称。请确认它不包含无效的字符或标点,且名称不太长") != -1)
                {
                    return false;
                }
                return false;
            }
        }
        /// <summary>
        /// 获取获得当前你选择的Excel Sheet的所有名字
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string[] GetExcelSheetNames(string filePath)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            int count = wb.Worksheets.Count;
            string[] names = new string[count];
            for (int i = 1; i <= count; i++)
            {
                names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name;
            }
            wb.Close(null, null, null);
            excelApp.Quit();
            wbs.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs);
            excelApp = null;
            wbs = null;
            wb = null;
            return names;
        }
        private void FillDataToDs(string itemid, string itemplu, string itemName)
        {
            DataRow[] rows = lblSelectDs.Tables["MSTM150_ITEM"].Select(string.Format("MSTM150_ITEMID=‘{0}‘", itemid));
            if (rows.Length == 0)
            {
                if (itemid.Trim() != string.Empty && itemplu.Trim() != string.Empty && itemName != string.Empty)
                {
                    DataRow dr;
                    dr = lblSelectDs.Tables["MSTM150_ITEM"].NewRow();
                    dr[MSTM150_ITEM.MSTM150_ITEMID] = itemid;
                    dr["MSTM151_PLUCD"] = itemplu;
                    dr["MSTM150_ITEMCNM"] = itemName;
                    dr["CheckRemove"] = "0";
                    lblSelectDs.Tables["MSTM150_ITEM"].Rows.Add(dr);
                }
                //else if (itemid.Trim() == string.Empty)
                //{
                //    string st = "导入的商品id不允许为空";
                //    sb.Append(st);
                //    sb.Append("\r\n");
                //}
                //else if (itemplu.Trim() == string.Empty)
                //{
                //    string st = "导入的商品编码不允许为空";
                //    sb.Append(st);
                //    sb.Append("\r\n");
                //}
                //else if (itemName.Trim() == string.Empty)
                //{
                //    string st = "导入的商品名称不允许为空";
                //    sb.Append(st);
                //    sb.Append("\r\n");
                //}
            }
            else if(rows.Length>0)
            {
                ExcelDS.Tables["MSTM150_ITEM"].ImportRow(rows[0]);
            }
        }
        private void gvSelectedItems_RowCountChanged(object sender, EventArgs e)
        {//导出按钮
            this.F9Property.Enable=(gvSelectedItems.RowCount == 0) ? false : true;
        }

//导入导出Excel 注意的是及时的关闭Excel,不然占用进程很麻烦,我调试了大半天太弄好的
时间: 2024-10-03 10:20:15

DevExpress XtraGrid 数据导出导入Excel的相关文章

Delphi 数据导出到Excel

好多办公软件特别是财务软件,都需要配备把数据导出到Excel,下面就来介绍两种数据导出方法 1.ADODB导出查询结果(此方法需要安装Excel) 2.二维表数据导出(根据Excel文件结构生成二进制文件流,不需要安装Excel) 3.如果涉及到复杂表头的(例如合并字段等),未做研究,下面也没介绍相关资料,请止步. 第一种,ADODB导出查询结果(此方法需要安装Excel) //uses DB, ADODB, ComObj, ComCtrls, excel2000, StdCtrls, adoi

将datagrid中数据导出到excel中 -------&lt;&lt;工作日志2014-6-6&gt;&gt;

1.下载log4j jar包,放入lib目录, 导入项目中   下载地址 http://logging.apache.org/ 2.创建log4j.properties 文件  目录 Src  下面是一个 log4j.properties的例子(注:来源于网上,非本人所写) ################################################################################ # 其语法:log4j.rootLogger = [ leve

DevExpress- GridControl数据导出到EXCEL

将DevExpress-GridControl数据导出到EXCEL,目前用过两种,一为利用GridControl函数操作,一为用流(IO)操作.区别在于前者可以将你在GridControl所见格式全部导入EXCEL,比如有时候我们在Bands里面拖拽出来的Title样式,后者最大优点在于速度很快,亲测10W条数据导出只需2秒左右; ? ? No.1:用GridControl函数导出数据到EXCEL,建议设置Options下OptionsPrint-AutoWidth=False,使导出后单元格宽

机房收费系统之vb中的MSFlexGrid控件中的数据导出为Excel的步骤

MSFlexGrid控件中的数据导出为Excel表格的方法有很多,我觉得它们都大同小异,总起来说就是vb先调用Excel,然后再将数据导入进去.在数据导出的过程中,我的收获如下,下面是我把MSFlexGrid控件的数据导出到Excel中的步骤. 1 首先确保 在工程中引用Microsoft Excel 14.0 Object Library   和  Microsoft ActiveX Data Objects 2.6 Libray 代码部分, <span style="font-size

db2数据导出导入

C:\Users\yexuxia>set db2instance=TCASHMAN C:\Users\yexuxia>db2(c) Copyright IBM Corporation 1993,2007DB2 客户机 10.5.0 的命令行处理器 db2 => connect to TCASHMAN user db2inst1 using '1qaz!QAZ' 数据库连接信息 数据库服务器         = DB2/AIX64 9.7.0 SQL 授权标识         = DB2I

支持将数据导出到Excel文档的时候设置单元格格式的.NET控件Spire.DataExport

Spire.DataExport for .NET是e-iceblue公司推出的一款数据导出类.NET控件.作为一款专业的数据导出控件,Spire.DataExport for .NET可以帮助开发人员轻松快速的从各种主流数据库中导出数据并存储于各种文件格式中.他支持从SQL Command, DataTable,ListView中导出数据并存储于MS Excel,MS Word, HTML, XML, PDF, MS Access, DBF, SQL Script, SYLK, DIF, CS

数据导出至Excel文件--好库编程网http://code1.okbase.net/codefile/SerializeHelper.cs_2012122018724_118.htm

using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; /// <summary> /// Excel操作类 /// </summary> /// Microsoft Excel 11.0 Obj

Oracle如何实现创建数据库、备份数据库及数据导出导入的一条龙操作

Oracle如何实现创建数据库.备份数据库及数据导出导入的一条龙操作 Oracle中对数据对象和数据的管理,无疑都是使用PL/SQL Developer来进行管理,该工具也提供给我们很多方便.快捷的操作,使得我们不再为Oracle本身丑陋.难用的UI而抱怨.由于我们一般都是建建表.查查数据的操作居多,较少会考虑系统的整个Oracle的完整备份操作.但是在我们一些发布操作中,我们必须考虑如何把Oracle的对象.表数据导出到Sql脚本中,并且把创建Oracle表空间.创建Oracle数据库的操作也

tablib把数据导出为Excel、JSON、CSV等格式的Py库(写入数据并导出exl)

#tablib把数据导出为Excel.JSON.CSV等格式的Py库 #python 3 import tablib #定义列标题 headers = ('1列', '2列', '3列', '4列', '5列') #需写入的数据,按照一行一行的输入 #元组数据的个数必须和列数一致 data = [('23','23','34','23','34'),('sadf','23','sdf','23','fsad')] #写入数据 mylist = tablib.Dataset(*data, head