惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
A
About on SuperTechFans
博客园 - Franky
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Martin Fowler
Martin Fowler
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Last Week in AI
Last Week in AI
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
V
V2EX
G
Google Developers Blog

博客园 - ROCk_IE

郎咸平——日本再陷美国式狙击 给大家推荐一个真正的免费空间,支持asp.net,PHP,多种数据库,空间容量无限 利用手中的股票做T+0 EIQ分析在物流系统中的运用 c# list 转数组函数 仿真软件介绍-AnyLogic IE与Firefox的CSS兼容大全 Gspace自动转到Gmail的解决方法 介绍一款令人叹为观止的Flex网络操作系统 【Firefox应用】用Gspace打造你的Gmail版移动硬盘 沃尔玛还是沃尔玛! B2C:看上去很美 淘宝VS沃尔玛:商业主流改朝换代 智慧供应链 合理物流管控成本 博客精灵 PK Windows Live Writer 一个北大人的工作感悟 by LLpig@YTHT CSS边框的设定方法 DIV边框样式设置 - ROCk_IE - 博客园 [转帖]一个非英语专业的人的自述:我如何用一年时间考上欧盟口译司
简单Excel导出与导入 - ROCk_IE - 博客园
ROCk_IE · 2009-08-17 · via 博客园 - ROCk_IE

   /// <summary>
    /// DataTableToExcel 的摘要说明
    /// </summary>
    public class DataTableToExcel
    {
        /// <summary>
        /// 由 DataSet 导出 Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="FileName"></param>      
        public static void DataTableToExcelAndDownload(System.Data.DataTable dt, string FileName)
        {
            HttpResponse resp = HttpContext.Current.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);      
            string colHeaders = "", ls_item = "";
            int i = 0;

            DataRow[] myRow = dt.Select("");

            //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
            for (i = 0; i < dt.Columns.Count; i++)
            {
                if (i == dt.Columns.Count - 1)
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            resp.Write(colHeaders);

            foreach (DataRow row in myRow)
            {
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == dt.Columns.Count - 1)
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }

                resp.Write(ls_item);
                ls_item = "";
            }

            resp.End();
        }

        /// <summary>
        /// 由 DataSet 导出 Excel ,自定义字段名
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="FileName"></param>      
        public static void DataTableToExcelAndDownload(System.Data.DataTable dt, string FileName,string[] cells)
        {
            HttpResponse resp = HttpContext.Current.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;

            DataRow[] myRow = dt.Select("");

            //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
            for (i = 0; i < cells.Length; i++)
            {
                if (i == cells.Length - 1)
                {
                    colHeaders += cells[i].ToString() + "\n";
                }
                else
                {
                    colHeaders += cells[i].ToString() + "\t";
                }
            }
            resp.Write(colHeaders);

            foreach (DataRow row in myRow)
            {
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == dt.Columns.Count - 1)
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }

                resp.Write(ls_item);
                ls_item = "";
            }

            resp.End();
        }

        /// <summary>
        /// 下载服务器端的文件到本地
        /// </summary>
        /// <param name="_Request"> </param>
        /// <param name="_Response"> </param>
        /// <param name="_fileName"> 目的文件名称 </param>
        /// <param name="_fullPath"> 源文件路径 </param>
        /// <param name="_speed"> 速度大小(1024000 -> 10k/s) </param>       
        public static bool DownloadFile(HttpRequest Request, HttpResponse Response,string fileName,string fullPath, long speed)
        {           
            try
            {
                FileStream myFile = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    Response.AddHeader("Accept-Ranges", "bytes");
                    Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    double pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)Math.Floor(1000 * pack / speed) + 1;
                    if (Request.Headers["Range"] != null)
                    {
                        Response.StatusCode = 206;
                        string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                    }
                    Response.AddHeader("Connection", "Keep-Alive");
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("GB2312")));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (Response.IsClientConnected)
                        {
                            Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();

                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        //*********************** Excel 导入功能 ***************************//

        /// <summary>
        /// 读取Excel文档中的数据到内存中
        /// </summary>
        /// <param name="Path"> 文件名称 </param>
        /// <returns> 返回一个数据集 </returns>
        public static DataSet ExcelToDataSet(string Path)
        {
            DataSet ds = new DataSet();

            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";

            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;

            strExcel = "select * from [Sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            myCommand.Fill(ds);

            return ds;
        }

        /// <summary>
        /// 将DataSet中的数据插入到SqlServer中
        /// </summary>
        /// <param name="ds"> 结果集 </param>
        /// <param name="TableName"> 表名 </param>
        /// <param name="MasterID"> 订单主表ID </param>
        public static void DataSetToSqlServer(DataSet ds,string TableName,string MasterID)
        {
            DataTable dt = new DataTable();
            long ID = Shove._Convert.StrToLong(MasterID,0);     //主表ID

            if (ds != null && ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string GoodNo = dt.Rows[i][0].ToString();
                    string GoodNorm = dt.Rows[i][1].ToString();
                    int Amount = Shove._Convert.StrToInt(dt.Rows[i][2].ToString(),0);

                    DAL.Procedures.P_DataTableToSqlServer(TableName, ID, GoodNo, GoodNorm, Amount);
                }
            }
        }

    }