zoukankan      html  css  js  c++  java
  • 导出文件 下载 Xls 文件

                #region 导出文件
                private static void ImportPage(HttpContext Context, string app, string entity, string id)
                {
                    #region 获取数据id
                    AppEntity.App AppObj = AppEntity.GetApp(app);
                    AppEntity.Entity En = AppObj.GetEntity(entity);
                    #endregion
                    string columns = Context.Request.Form["columns"];
                    string striphtml = Context.Request.Form["striphtml"];
                    XmlDocument ColDom = new XmlDocument();
                    Hashtable param = new Hashtable();
                    param.Add("appsetting", AppObj.AppDom);
                    param.Add("entitysetting", En.EntityDom);
                    param.Add("urn:functions-sbsinc-com:ext", new SBS.Common.XslExtensionObject());
                    param.Add("urn:functions-sbsinc-com:AppEntity", new SBS.AppEntity.AppEntityXslExtension());
                    param.Add("app", app);
                    param.Add("entity", entity);
                    param.Add("action", "export");
                    param.Add("columns", ColDom);
                    string Folder = AppEntity.GetAppFolder() + app + "http://www.cnblogs.com/jacd/admin/file://entity//" + entity + "http://www.cnblogs.com/jacd/admin/file://data//";
                    string html = SBS.Common.Convert.xml2html("<root/>", AppEntity.GetThemePath() + "common\\import.xsl", param);
                    Context.Response.Write(html);
                }
                private static void DownTemplate(HttpContext Context, string app, string entity, string id)
                {
                    #region 获取数据id
                    AppEntity.App AppObj = AppEntity.GetApp(app);
                    AppEntity.Entity En = AppObj.GetEntity(entity);
                    var columns = En.columns.ToHashSet();
                    var sysColumnDict = AppEntity.GetAppBuilderSetting().Descendants("syscol").Elements("col").Select(
                        n => n.GetAttrValue("name")).ToHashSet();
                    #endregion
                    sysColumnDict.Remove("title");
                    sysColumnDict.Remove("description");
                    columns.ExceptWith(sysColumnDict);
                    string filename = AppObj.name + "-" + En.title + ".csv";
                    StreamWriter sw = new StreamWriter(Context.Response.OutputStream, Encoding.UTF8);
                    StringBuilder sb = new StringBuilder();
                    foreach (var c in columns)
                    {
                        sb.Append(c + ",");
                    }
                    sw.Write(sb.ToString().Substring(0, sb.Length - 1));
                    sw.Write("\r\n");
                    if (filename != "")
                    {
                        Context.Response.ContentEncoding = Encoding.UTF8;
                        Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                        //   Context.Response.ContentType = "application/octet-stream";
                        //   Context.Response.ContentType = "application/csv";
                        sw.Close();
                        Context.Response.End();
                    }
                }
                #region 下载 Xls 文件
                private static void DownTemplateXls(HttpContext Context, string app, string entity, string id)
                {
                    #region 获取数据id
                    AppEntity.App AppObj = AppEntity.GetApp(app);
                    AppEntity.Entity En = AppObj.GetEntity(entity);
                    string tableName = "ColumnExample";
                    var columns = En.columns.ToHashSet();
                    var sysColumnDict = AppEntity.GetAppBuilderSetting().Descendants("syscol").Elements("col").Select(
                        n => n.GetAttrValue("name")).ToHashSet();
                    sysColumnDict.Remove("title");
                    sysColumnDict.Remove("description");
                    columns.ExceptWith(sysColumnDict);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(" CREATE TABLE " + tableName + " (");
                    foreach (var c in columns)
                    {
                        sb.Append(c + " VARCHAR(99),");
                    }
                    string CreateSql = sb.ToString();
                    CreateSql = CreateSql.Trim(',');
                    CreateSql = CreateSql + ")";
                    #endregion
                    string newFile = (Context.Server.MapPath(".") + "\\" + "TableColumn.xls");
                    File.Delete(newFile);
                    File.Copy(@"D:\tasktoday.353.us\fb.tasktoday.com\TableColumn.xls", newFile, true);
                    string cnStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" +
                        newFile + ";Extended Properties=Excel 8.0";
                    using (var cn = new OleDbConnection(cnStr))
                    {
                        cn.Open();
                        var cmd = new OleDbCommand(CreateSql, cn);
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        cn.Close();
                    }
                    MemoryStream ms = new MemoryStream(File.ReadAllBytes(newFile));
                    ms.WriteTo(Context.Response.OutputStream);
                    ms.Close();
                    Context.Response.ContentEncoding = Encoding.UTF8;
                    string filename = AppObj.name + "-" + En.title + ".xls";
                    Context.Response.AddHeader("Content-Disposition", "attachment; filename= " + filename);
                    Context.Response.ContentType = "application/ms-excel";
                    Context.Response.End();
                }
                #endregion
                #endregion

                /// <summary>
                
    /// CSV文件导入TABLE
                
    /// </summary>
                
    /// <param name="Context"></param>
                
    /// <param name="app"></param>
                
    /// <param name="entity"></param>
                private static void FileImport(HttpContext Context, string app, string entity)
                {
                    AppEntity.Entity En = AppEntity.GetApp(app).GetEntity(entity);
                    string Doublequotes = Context.Request.Form["Doublequotes"];
                    char SplitStr = Context.Request.Form["SplitStr"][0];
                    HttpPostedFile httpFile = Context.Request.Files["CSVfile"];
                    string url = "/common/?app=" + app + "&entity=" + entity + "&action=import";
                    if (httpFile.ContentLength < 1)
                    {
                        Context.Response.Write("文件不能为空");
                        return;
                    }
                    if (httpFile.FileName.ToUpper().IndexOf("csv".ToUpper()) > 0)
                    { 
                        WriteCSV(Context, En, Doublequotes, httpFile, url);
                    }
                    if (httpFile.FileName.ToUpper().IndexOf("xls".ToUpper()) > 0 )
                    { 
                        WriteXls(Context, En, Doublequotes, httpFile, url);
                    }

                } 
                private static void WriteCSV(HttpContext Context, AppEntity.Entity En, string Doublequotes, HttpPostedFile httpFile, string url)
                { 
                    string dir = Path.GetTempPath();
                    string fileName = Path.Combine(dir, "importdata.csv");
                    File.Delete(fileName);
                    httpFile.SaveAs(fileName);
                    string tableName = "[importdata.csv]";
                    string cnStr =
                      "Provider=Microsoft.Jet.OLEDB.4.0;" +
                      "Extended Properties='text;HDR=Yes;FMT=Delimited';" +
                      "Data Source=" + dir + ";";
                    WriteToTable(cnStr,Context, En, Doublequotes, url, dir, tableName);
                }
                private static void WriteXls(HttpContext Context, AppEntity.Entity En, string Doublequotes, HttpPostedFile httpFile, string url)
                {
                    string dir = Context.Server.MapPath(".");
                    string fileName = Path.Combine(dir, "TableColumnEntity.xls"); 
                    File.Delete(fileName);
                    httpFile.SaveAs(fileName);
                    string tableName = "[ColumnExample$]";
                    string cnStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" +
                     fileName + ";Extended Properties=Excel 8.0"
                    WriteToTable(cnStr,Context, En, Doublequotes, url, fileName, tableName);
                }

                private static void WriteToTable(string cnStr,HttpContext Context, AppEntity.Entity En, string Doublequotes, string url, string DataSouce, string tableName)
                {
                  
                    DataTable dTab = new DataTable();
                    int ValueCount = 0;
                    using (var cn = new OleDbConnection(cnStr))
                    {
                        cn.Open();
                        string sql = "SELECT * FROM " + tableName;
                        OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
                        da.Fill(dTab);
                        for (int i = 0; i < dTab.Rows.Count; i++)
                        {
                            AppEntity.Record row = En.Create();
                            foreach (DataColumn column in dTab.Columns)
                            {
                                string value = dTab.Rows[i][column].ToString();
                                string ColumnName = column.ColumnName;
                                if (Doublequotes == "N")
                                {
                                    value = value.Trim('"');
                                }
                                if (En.GetColumn(ColumnName).type == "double" ||
                                    En.GetColumn(ColumnName).type == "integer")
                                {
                                        value=(value.ToDouble(0)).ToString();
                                }
                                if (En.GetColumn(ColumnName).type == "datetime" ||
                                    En.GetColumn(ColumnName).type == "date")
                                {
                                    value = SBS.Common.Utility.GetNowTime(value.ToDateTime(DateTime.Now));
                                }
                                row.SetColumnValue(ColumnName, value);
                            }
                            try
                            {
                                row.Add();
                                ValueCount++;
                            }
                            catch
                            {
                            }
                        } 
                        Context.Response.Redirect(url + "&ValueCount=" + ValueCount);
                    }
                }
  • 相关阅读:
    There is an overlap in the region chain修复
    There is an overlap in the region chain
    region xx not deployed on any region server
    python 中的re模块,正则表达式
    TCP粘包问题解析与解决
    yield from
    Git push提交时报错Permission denied(publickey)...Please make sure you have the correct access rights and the repository exists.
    mysql 中Varchar 与char的区别
    Mysql 字符集及排序规则
    请实现一个装饰器,限制该函数被调用的频率,如10秒一次
  • 原文地址:https://www.cnblogs.com/jacd/p/2547937.html
Copyright © 2011-2022 走看看