winform导入导出excel,后台动态添加控件

Posted system_kk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winform导入导出excel,后台动态添加控件相关的知识,希望对你有一定的参考价值。

思路:

导入:

1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();)

2, 获取用户选择文件的后缀名(string extension = Path.GetExtension(fileDialog.FileName).ToLower();),并设置允许后缀文件名;

3,NPOI转datetable,遍历tatetable转成实体类列表并入库;

导出:

1, 创建提示用户保存类,SaveFileDialog saveFileDialog = new SaveFileDialog(),设置允许导出文件名,对话框显示信息等属性;

2,saveFileDialog.FileName.Length>0,sql转datetable,NPOI创建文件(设置保存路径 saveFileDialog.FileName)

动态添加控件注意:

1,在panal添加对应控件,便于数据太多可以下拉(AutoScroll=true);

2,设置new Point(x,y)坐标位置,控件大小调整;特别是坐标不好处理,现在页面上设置排版,并记录x,y 记录;

3,给与对应控件添加响应事件(如双击全选等等)

4,保存时后台查找控件对应值,winform没有webform的findcontrol方法,故网上找到帮助类(如下),但原理一样都是从对应Control下查找已添加类,注意动态添加控件时,命名需有规则,便于查找:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows.Forms;
 6 
 7 namespace webfrom.common
 8 {
 9    public static class ControlUtil
10     {
11         /// <summary>
12         /// 按名称查找控件
13         /// </summary>
14         /// <param name="parentControl">查找控件的父容器控件</param>
15         /// <param name="findCtrlName">查找控件名称</param>
16         /// <returns>若没有查找到返回NULL</returns>
17         public static Control FindControl(this Control parentControl, string findCtrlName)
18         {
19             Control _findedControl = null;
20             if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
21             {
22                 foreach (Control ctrl in parentControl.Controls)
23                 {
24                     if (ctrl.Name.Equals(findCtrlName))
25                     {
26                         _findedControl = ctrl;
27                         break;
28                     }
29                 }
30             }
31             return _findedControl;
32         }
33         /// <summary>
34         /// 将Control转换某种控件类型
35         /// </summary>
36         /// <typeparam name="T">控件类型</typeparam>
37         /// <param name="control">Control</param>
38         /// <param name="result">转换结果</param>
39         /// <returns>若成功则返回控件;若失败则返回NULL</returns>
40         public static T Cast<T>(this Control control, out bool result) where T : Control
41         {
42             result = false;
43             T _castCtrl = null;
44             if (control != null)
45             {
46                 if (control is T)
47                 {
48                     try
49                     {
50                         _castCtrl = control as T;
51                         result = true;
52                     }
53                     catch (Exception ex)
54                     {
55                         result = false;
56                     }
57                 }
58             }
59             return _castCtrl;
60         }
61     }
62 
63    //public class comBoBoxEx : System.Windows.Forms.ComboBox
64    //{
65    //    public bool isWheel = false;
66    //    public string strComB = null;
67    //    protected override void OnMouseWheel(System.Windows.Forms.MouseEventArgs e)
68    //    {
69    //        strComB = Text;
70    //        isWheel = true;
71    //    }
72 
73    //    protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
74    //    {
75    //        base.OnMouseDown(e);
76    //        isWheel = false;
77 
78    //    }
79 
80    //    protected override void OnTextChanged(EventArgs e)
81    //    {
82    //        base.OnTextChanged(e);
83    //        if (isWheel)
84    //        {
85    //            Text = strComB;
86    //        }
87    //    }
88    //}
89 }
View Code

 

其他:

鼠标滚动,禁用;窗口置顶;

 

所有后台代码:

   1 using System;
   2 using System.Collections.Generic;
   3 using System.ComponentModel;
   4 using System.Data;
   5 using System.Drawing;
   6 using System.Linq;
   7 using System.Text;
   8 using System.Windows.Forms;
   9 using webframework.common;
  10 using System.Collections;
  11 using System.IO;
  12 using webfrom.common;
  13 using System.Text.RegularExpressions;
  14 using webfrom.bll;
  15 using webfrom.model;
  16 using mysql.Data.MySqlClient;
  17 using System.Data.SqlClient;
  18 
  19 namespace webfrom.trip
  20 {
  21     public partial class tripmain : Form, IMessageFilter
  22     {
  23         //当前登陆用户
  24         public string Username { get; set; }
  25         //乘客人数
  26         public int PsgCount { get; set; }
  27         //订单ID
  28         public string OrderID { get; set; }
  29         //tt订单号
  30         public string OrderNO { get; set; }
  31         //平台id
  32         public string orderFrom { get; set; }
  33         //快递单号
  34         public string ExpNo { get; set; }
  35 
  36 
  37         public tripmain()
  38         {
  39             InitializeComponent();
  40         }
  41         public bool PreFilterMessage(ref Message m)
  42         {
  43             if (m.Msg == 522)
  44             {
  45                 return true;
  46             }
  47             else
  48             {
  49                 return false;
  50             }
  51         }
  52         //导入
  53         private void btnimport_Click(object sender, EventArgs e)
  54         {
  55             lbl_msg.Text = "";
  56             //初始化一个OpenFileDialog类
  57             OpenFileDialog fileDialog = new OpenFileDialog();
  58             //判断用户是否正确的选择了文件
  59             if (fileDialog.ShowDialog() == DialogResult.OK)
  60             {
  61                 //获取用户选择文件的后缀名
  62                 string extension = Path.GetExtension(fileDialog.FileName).ToLower();
  63                 //声明允许的后缀名
  64                 string[] str = new string[] { ".xls", ".xlsx", ".csv" };
  65                 if (!((IList)str).Contains(extension))
  66                 {
  67                     //MessageBox.Show("仅能导入xls,xlsx,csv文件!");
  68                     lbl_msg.Text = "提示信息:仅能导入xls,xlsx,csv文件!";
  69                 }
  70                 else
  71                 {
  72                     DataTable dt = new DataTable();
  73                     switch (extension)
  74                     {
  75                         case ".xlsx":
  76                             dt = common.ExcelHelper.ExcelToTableForXLSX(fileDialog.FileName);
  77                             break;
  78                         case ".xls":
  79                             dt = common.ExcelHelper.GetExcelDataAsTableNPOI(fileDialog.FileName);
  80                             break;
  81                         case ".csv":
  82                             dt = common.CSVUtil.getCsvDataByTitle(fileDialog.FileName, "业务单号", null);
  83                             break;
  84                         default:
  85                             break;
  86                     }
  87                     if (dt.Rows.Count > 0)
  88                     {
  89                         int error = 0;
  90                         int count = 0;
  91                         try
  92                         {
  93                             List<modelt_printexpress> list = new List<modelt_printexpress>();
  94                             modelt_printexpress m;
  95                             DateTime dtnow = DateTime.Now;
  96                             string orderid = string.Empty;
  97 
  98                             foreach (DataRow dr in dt.Rows)
  99                             {
 100                                 count++;
 101                                 orderid = dr["业务单号"].ToString().Trim();
 102                                 if (string.IsNullOrEmpty(orderid))
 103                                     continue;
 104                                 m = new modelt_printexpress();
 105                                 #region model赋值
 106                                 m.expcompany = dr["物流公司"].ToString().Trim();
 107                                 m.busno = dr["业务单号"].ToString().Trim();//对应国内tt订单号
 108                                 m.expno = dr["运单号"].ToString().Trim();
 109                                 m.fworkaddress = dr["寄件单位"].ToString().Trim();
 110                                 m.fname = dr["寄件人姓名"].ToString().Trim();
 111                                 m.ftelno = dr["寄件人电话"].ToString().Trim();
 112                                 m.fmobileno = dr["寄件人手机"].ToString().Trim();
 113                                 m.fprovince = dr["寄件人省"].ToString().Trim();
 114                                 m.fcity = dr["寄件人市"].ToString().Trim();
 115                                 m.fregion = dr["寄件区/县"].ToString().Trim();
 116                                 m.faddress = dr["寄件人地址"].ToString().Trim();
 117                                 m.fpostcode = dr["寄件人邮编"].ToString().Trim();
 118                                 m.tname = dr["收件人姓名"].ToString().Trim();
 119                                 m.ttelno = dr["收件人电话"].ToString().Trim();
 120                                 m.tmobileno = dr["收件人手机"].ToString().Trim();
 121                                 m.tprovince = dr["收件省"].ToString().Trim();
 122                                 m.tcity = dr["收件市"].ToString().Trim();
 123                                 m.tregion = dr["收件区/县"].ToString().Trim();
 124                                 m.taddress = dr["收件人地址"].ToString().Trim();
 125                                 m.tpostcode = dr["收件邮政编码"].ToString().Trim();
 126                                 m.exppay = StringUtils.StrToDecimal(dr["运费"].ToString().Trim(), 0);
 127                                 m.orderprice = StringUtils.StrToDecimal(dr["订单金额"].ToString().Trim(), 0);
 128                                 m.itemname = dr["商品名称"].ToString().Trim();
 129                                 m.itemcode = dr["商品编码"].ToString().Trim();
 130                                 m.itemattribute = dr["销售属性"].ToString().Trim();
 131                                 m.itemprice = StringUtils.StrToDecimal(dr["商品金额"].ToString().Trim(), 0);
 132                                 m.itemacount = StringUtils.StrToInt(dr["数量"].ToString().Trim(), 0);
 133                                 m.leavemsg = dr["留言"].ToString().Trim();
 134                                 m.note = dr["备注"].ToString().Trim();
 135                                 m.operater = this.Username;
 136                                 m.creattime = dtnow;
 137                                 #endregion
 138                                 list.Add(m);
 139                             }
 140                             string msg = string.Empty;
 141                             new bllprintexpress().InsertList(list, Config.CONSQL_172_16_6_1_WRITE, ref msg);
 142                             //MessageBox.Show("数据导入完毕【文件总数:" + dt.Rows.Count + " 导入" + msg + "--未匹配tt订单号:" + error + "】");
 143                             lbl_msg.Text = "提示信息:" + "数据导入完毕【文件总数:" + dt.Rows.Count + " 导入" + msg + "--未匹配tt订单号:" + error + "";
 144 
 145 
 146                         }
 147                         catch (Exception ex)
 148                         {
 149                             //MessageBox.Show("导入数据报错:" + ex.Message);
 150                             lbl_msg.Text = "提示信息:" + "导入数据报错:" + ex.Message;
 151                         }
 152                     }
 153                     else
 154                     {
 155                         //MessageBox.Show("您选择的文件报表中没有数据");
 156                         lbl_msg.Text = "提示信息:" + "您选择的文件报表中没有数据";
 157                     }
 158                 }
 159             }
 160         }
 161         //导出
 162         private void btnexport_Click(object sender, EventArgs e)
 163         {
 164             try
 165             {
 166                 lbl_msg.Text = "";
 167                 DateTime dtbegin = Convert.ToDateTime(dtpbegin.Value.ToString("yyyy-MM-dd"));
 168                 DateTime dtend = Convert.ToDateTime(dtpend.Value.ToString("yyyy-MM-dd"));
 169                 if ((dtend - dtbegin).Days > 30)
 170                 {
 171                     //MessageBox.Show("航班日期跨度不能超过30天");
 172                     lbl_msg.Text = "提示信息:" + "航班日期跨度不能超过30天";
 173                     dtpbegin.Focus();
 174                     return;
 175                 }
 176                 if (dtend < dtbegin)
 177                 {
 178                     //MessageBox.Show("航班开始日期不能大于结束日期");
 179                     lbl_msg.Text = "提示信息:" + "航班开始日期不能大于结束日期";
 180                     dtpbegin.Focus();
 181                     return;
 182                 }
 183 
 184                 SaveFileDialog saveFileDialog = new SaveFileDialog();
 185                 saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";
 186                 saveFileDialog.FilterIndex = 0;
 187                 saveFileDialog.RestoreDirectory = true;
 188                 saveFileDialog.CreatePrompt = true;
 189                 saveFileDialog.Title = "导出文件保存路径";
 190                 saveFileDialog.ShowDialog();
 191                 string strName = saveFileDialog.FileName;
 192                 if (strName.Length != 0)
 193                 {
 194                     string sql = "SELECT o.id orderid ,o.orderNo,jd.receiver,jd.receiverPhone,jd.postCode,jd.postAddress " +
 195                    "FROM t_order AS o " +
 196                    "LEFT JOIN t_journey AS jo ON o.id = jo.orderId " +
 197                    "LEFT JOIN t_journeypassenger AS jp ON jo.id = jp.journeyId " +
 198                    "LEFT JOIN t_passenger AS p ON jp.passengerId = p.id " +
 199                    "LEFT JOIN t_travel AS tr ON jp.id = tr.journeyPassengerId " +
 200                    "RIGHT JOIN t_journeydetail AS jd ON o.id = jd.orderId  " +
 201                    "WHERE 1=1 AND o.orderFrom=1 " +
 202                    "AND  (jp.pTikState IS NULL OR  jp.pTikState!=1) " +
 203                    "AND jd.postAddress <>\'\' " +
 204                    "AND (o.orderState=1 OR o.orderState=3 OR o.orderState=7) " +
 205                    "AND jo.takeoffDate >=\'" + dtbegin.ToString("yyyy-MM-dd") + "\' " +
 206                    "AND jo.takeoffDate <=\'" + dtend.ToString("yyyy-MM-dd") + "\'  " +
 207                    "AND (tr.printState IS NULL OR tr.printState=0) " +
 208                    "AND jd.isTra=1 AND  (jd.isTra=1 AND jd.isTraKf <> 0) " +
 209                         //"AND jd.isTra=1 AND  ((jd.isTra=1 AND jd.isTraKf <> 0) or  jd.isTraKf=1)  " +
 210                         //" and (jd.traAddress<>\'\' or   jd.isTraKf=1) or

以上是关于winform导入导出excel,后台动态添加控件的主要内容,如果未能解决你的问题,请参考以下文章

C# Excel控件

c#如何在winform中打开一个excel文档呢

C#winform中如何把表导出到EXCEL

C#winform怎么弄出类似于excel的表格?简单点的就好

winform用户控件动态创建添加控件timer控件控件联动

winform窗体 Treeview控件子节点动态添加图片