• Asp.net 模板下载和导入到DataTable中


    HTML页面:

            <tr>
                <td colspan="8" style="text-align: left; border: 1px;">
                    <asp:FileUpload ID="FileUpload1" runat="server" CssClass="dfFile" Width="350px" />
                    <asp:Button ID="btnImport" runat="server" Text="导入" CssClass="scbtn" OnClientClick="return LoadFile();"
                        OnClick="btnImport_Click" />
                    <asp:Button ID="btnDownLoad" runat="server" Text="模板下载" CssClass="scbtn" OnClick="btnDownLoad_Click" />
                </td>
            </tr>

    Asp.net后台:

        #region 导入
            /// <summary>
            /// 导入
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnImport_Click(object sender, EventArgs e)
            {
                string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//获得文件的扩展名
                if (IsXls != ".xls" && IsXls != ".xlsx")
                {
                    ShowMessageBox("只可以选择Excel文件");
                    return;
                }
                HttpPostedFile file = this.FileUpload1.PostedFile;
    
                string filename = FileUpload1.FileName;              //获取Execle文件名
                string filePath = Server.MapPath("../StorageCheck/CheckUpFiles/" + FileUpload1.FileName);
                file.SaveAs(filePath);
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
                try
                {
                    DataSet ds = ExcelSqlConnection(filePath, filename);  //调用自定义方法
                    DataTable dt = ds.Tables[0];
    
                    //循环移除DataTable中的空行
                    List<DataRow> removelist = new List<DataRow>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        bool rowIsNull = true; //标记是否有空行
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                            {
    
                                rowIsNull = false;
                            }
                        }
                        if (rowIsNull)
                        {
                            removelist.Add(dt.Rows[i]);
                        }
                    }
                    for (int i = 0; i < removelist.Count; i++)
                    {
                        dt.Rows.Remove(removelist[i]);
                    }
    
                    string detName = "";
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detName += dr["箱号"].ToString() + "[" + dr["盒号"].ToString() + "]" + "[" + dr["起始卡号"].ToString() + "]" + "[" + dr["结束卡号"].ToString() + "]" +
                              "[" + dr["应有数量/张"].ToString() + "]" + "[" + dr["实际数量/张"].ToString() + "]" + "[" + dr["缺卡卡号"].ToString() + "];";
                            detId += dr["箱号"].ToString() + "," + dr["盒号"].ToString() + "," + dr["起始卡号"].ToString() + "," + dr["结束卡号"].ToString() + "," +
                                     dr["应有数量/张"].ToString() + "," + dr["实际数量/张"].ToString() + "," + dr["缺卡卡号"].ToString();
    
                            if (string.IsNullOrEmpty(dr["缺卡卡号"].ToString()))
                            {
                                detId += "0" + ";";
                            }
                        }
                        hf_CheckId.Value = detId.TrimEnd(';');
                    }
                }
                catch
                { }
                finally
                {
                    fs.Flush(); //释放流
                    fs.Close();//关闭流
                }
            }
            #endregion
    
            #region 模板下载
            /// <summary>
            /// 模板下载
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnDownLoad_Click(object sender, EventArgs e)
            {
                //filePath为文件在服务器上的地址
                string excelFile = Server.MapPath("../StorageCheck/DownLoad/白卡入库导入模板.xls");
                FileInfo fi = new FileInfo(excelFile);
                HttpResponse contextResponse = HttpContext.Current.Response;
                contextResponse.Clear();
                contextResponse.Buffer = true;
                contextResponse.Charset = "GB2312"; //设置类型 
                contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", excelFile)); //定义输出文件和文件名 
                contextResponse.AppendHeader("Content-Length", fi.Length.ToString());
                contextResponse.ContentEncoding = Encoding.Default;
                contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
    
                contextResponse.WriteFile(fi.FullName);
                contextResponse.Flush();
                contextResponse.End();
            }
            #endregion
    
            #region 读取Excel数据
            /// <summary>
            /// 读取Excel数据
            /// </summary>
            /// <param name="filepath">Excel服务器路径</param>
            /// <param name="tableName">Excel表名称</param>
            /// <returns></returns>
            public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
            {
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
                OleDbConnection ExcelConn = new OleDbConnection(strCon);
                try
                {
                    string strCom = string.Format("SELECT * FROM [Sheet1$]");
                    //string strCom = "select * from [" + tableName + "]";
                    ExcelConn.Open();
                    OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
                    DataSet ds = new DataSet();
                    myCommand.Fill(ds, "[" + tableName + "$]");
                    ExcelConn.Close();
                    return ds;
                }
                catch
                {
                    ExcelConn.Close();
                    return null;
                }
            }
            #endregion
  • 相关阅读:
    彩食鲜架构团队风采
    钉钉的sonar集成通知
    django学习,session与cookie
    flask框架
    logging日志从开始到放弃
    你这么年轻,总得做些什么吧(致那些还未定型的程序员)
    悲观锁,乐观锁
    商城中的猜你喜欢是怎么实现的
    MemCache与redis
    如何使用go打出hell word
  • 原文地址:https://www.cnblogs.com/rwh871212/p/5163452.html
Copyright © 2020-2023  润新知