解析Winform中导入导出Excel实现代码

 代码如下 复制代码

以前在B/s上写过EXCEL导入导出,其实代码都是差不多的,本人第一次写笔记,说的可能有些模糊

#region 导出EXCEL
        private void DataGridViewToExcel(DataTable dt, string filename)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Execl files (*.xls)|*.xls";
                dlg.FilterIndex = 0;
                dlg.RestoreDirectory = true;
                dlg.Title = "保存为Excel文件";
                dlg.FileName = filename;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Stream myStream;
                    myStream = dlg.OpenFile();
                    StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                    string colHeaders = "", ls_item = "";
                    //写入列标题   
                    colHeaders += "部门" + "t";
                    colHeaders += "登录账号" + "t";
                    colHeaders += "姓名" + "t";
                    colHeaders += "密码" + "t";
                    colHeaders += "电话" + "t";
                    colHeaders += "手机" + "t";
                    colHeaders += "Email" + "t";
                    colHeaders += "生日" + "t";
                    colHeaders += "过期时间";
                    sw.WriteLine(colHeaders);
                    DataRow[] myRow = dt.Select();
                    //写入列内容   
                    foreach (DataRow row in myRow)
                    {
                        ls_item += row["dept_name"].ToString() + "t";
                        ls_item += row["user_loginName"].ToString() + "t";
                        ls_item += row["user_realName"].ToString() + "t";
                        ls_item += "" + "t";
                        ls_item += row["user_telephone"].ToString() + "t";
                        ls_item += row["user_mobile"].ToString() + "t";
                        ls_item += row["user_email"].ToString() + "t";
                        ls_item += row["user_birthday"].ToString() + "t";
                        ls_item += row["user_expiredTime"].ToString();
                        sw.WriteLine(ls_item);
                        ls_item = "";
                    }
                    sw.Close();
                    myStream.Close();
                    MessageBox.Show("导出[" + filename + "]成功", "提示");

                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        #endregion

 

#region Excel导入

private void tsinuser_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "表格文件 (*.xls)|*.xls";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                InExcelData(openFileDialog.FileName);
            }
        }
        private bool InExcelData(string filePath)
        {
            try
            {
                HG_dms_folderEntity folderEnt = new HG_dms_folderEntity(); string folderid;
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;";

                OleDbConnection con = new OleDbConnection(strConn);
                con.Open();
                string[] names = GetExcelSheetNames(con);//GetExcelSheetNames(filePath);
                if (names != null)
                {
                    if (names.Length > 0)
                    {
                        foreach (string name in names)
                        {
                            OleDbCommand cmd = con.CreateCommand();
                            cmd.CommandText = string.Format(" select * from [{0}]", name);//[sheetName$]要如此格式
                            OleDbDataReader odr = cmd.ExecuteReader();

                            while (odr.Read())
                            {
                                if (odr[0].ToString() != "")
                                {
                                    if (odr[0].ToString() == "部门")//过滤列头 按你的实际Excel文件
                                        continue;
                                    if (userLogic.CheckUserLogin(odr[1].ToString()) == 0)
                                    {
                                        ……………………写入数据库

                                    }
                                }
                            }
                            odr.Close();
                        }
                    }
                }
                con.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 查询表名
        /// </summary>
        /// <param name="con"></param>
        /// <returns></returns>
        public static string[] GetExcelSheetNames(OleDbConnection con)
        {
            try
            {
                DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });//检索Excel的架构信息
                var sheet = new string[dt.Rows.Count];
                for (int i = 0, j = dt.Rows.Count; i < j; i++)
                {
                    sheet[i] = dt.Rows[i]["TABLE_NAME"].ToString();
                }
                return sheet;
            }
            catch
            {
                return null;
            }
        }

#endregion

 

时间: 2024-12-22 01:20:36

解析Winform中导入导出Excel实现代码的相关文章

从SQL Server中导入/导出 Excel 的基本方法

excel|server 从SQL Server中导入/导出 Excel 的基本方法 /*===================  导入/导出 Excel 的基本方法 ===================*/ 从Excel文件中,导入数据到SQL数据库中,很简单,直接用下面的语句: /*===================================================================*/--如果接受数据导入的表已经存在insert into 表 select

js导入导出excel(实例代码)_javascript技巧

导入: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml" ><head>     <title>Untitled Page</title></head><script language="javascript" type="text/javascript">function importXLS(fileName){ 

C#中导入导出Excel的相关问题

问题描述 现在有一个Excel模版,需要把里面的表的样式.图片.文字信息全部导入,呆修改后再按原样导出,请问能不能实现啊?网上找了一些资料,导入之后,样式就变了 解决方案 解决方案二:?您要導人到那?又要導出至那?

ASP.NET Core 导入导出Excel xlsx 文件实例_实用技巧

ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Linux和Mac. EPPlus.Core 是基于EPPlus 更改而来,在Linux 下需要安装libgdiplus . EPPlus:http://epplus.codeplex.com/ EPPlus.Core:https://github.com/VahidN/EPPlus.Core 下面在A

PHP导入导出Excel代码_php技巧

一.导入 导入需要使用能读取Excel的组件,网上也有比较好的组件,这里分享我使用的:下载  提取码:vxyn.(注意两个文件有引用关系) <?php //传入要导入的Excel的文件名 function import_to_DB($filename) { require_once'reader.php'; $data = new Spreadsheet_Excel_Reader(); //创建读取Excel的对象 $data->setOutputEncoding('utf-8'); //设置

Java利用POI实现导入导出Excel表格示例代码_java

介绍 Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组件组成,其中有用于操作Excel格式文件的HSSF和用于操作Word的HWPF,在各种组件中目前只有用于操作Excel的HSSF相对成熟.官方主页http://poi.apache.org/index.html,API文档http://poi.apache.org/apidocs/index.html 实现 已经在代码中加入了完整的注释. import java.io.FileInputSt

php导入导出excel实例_php实例

这里实现的PHP导入导出excel功能用到的是开源PHPExcel,执行下面的操作之前请先下载该类库文件,官方网站:http://www.codeplex.com/PHPExcel,官网案例代码很多,导出pdf什么的都有,这里主要介绍PHP导入导出excel的功能,导出excel文件是office2007格式,同时兼容2003. php导入excel导入的excel文件的数据格式,截图如下:下面是将该excel文件的数据导入到数据库的具体代码: 复制代码 代码如下: <?phprequire_o

.net客户端导出Excel实现代码及注意事项_实用技巧

客户端导出excel 复制代码 代码如下: /* * 将DataGrid导出为Excel文件 * * @param strTitle 文件标题 * @param dgData 待导出的DataGrid * @param iStartCol 起始列序号 * @param iEndCol 结束列序号 * * 创建人: calvin * 创建日期: 2005-10-08 * 修改人: * 修改日期:**/ function DataGrid2Excel(strTitle, dgData, iStart

导入导出excel表

问题描述 c#怎样导入导出excel表?(最好提供一个示例代码及教程) 解决方案 解决方案二:可以引用EXCEL的Com控件,但很麻烦.网上很多第三方操作的控件,自己可以找一下,比如Aspose.Cell,FarPoint,等解决方案三:先要添加com控件,然后才能使用.以下是我做的一个系统输出到Execl表格的代码,供你参考:privatevoidtoolStripButton_print_Click(objectsender,EventArgse){intRCount=dataGridVie