C#的一个较为完整的FileHelper

151 阅读7分钟
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.UI;

namespace WX_Card.CardUtility
{
    public class FileHelper
    {
        /// <summary>
        /// 读取表格到Table
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public DataSet ExcelToDS(string Path)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataSet ds = null;
            try
            {
                //获取动态名称  
                //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等   
                DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                //包含excel中表名的字符串数组  
                string[] strTableNames = new string[dtSheetName.Rows.Count];
                for (int k = 0; k < dtSheetName.Rows.Count; k++)
                {
                    strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
                }
                if (strTableNames.Count() > 0)
                {
                    OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[0]), conn);
                    ds = new DataSet();
                    odda.Fill(ds, strTableNames[0]);
                }
            }
            catch
            {
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }
        /// <summary>
        /// 读取表格到Table
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public DataSet ExcelToDSNew(string Path, bool hasheader = false)
        {
            string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";" + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataSet ds = null;
            try
            {
                //获取动态名称  
                //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等   
                DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                //包含excel中表名的字符串数组  
                string[] strTableNames = new string[dtSheetName.Rows.Count];
                for (int k = 0; k < dtSheetName.Rows.Count; k++)
                {
                    strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
                }
                if (strTableNames.Count() > 0)
                {
                    OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[0]), conn);
                    ds = new DataSet();
                    odda.Fill(ds, strTableNames[0]);
                }

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

                    //将表格第一行设置为标题
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        string columnname = "F" + (i + 1).ToString();
                        if (ds.Tables[0].Columns[i].ColumnName.Equals(columnname))
                        {
                            ds.Tables[0].Columns[i].ColumnName = ds.Tables[0].Rows[0][columnname].ToString();
                        }
                    }
                    ds.Tables[0].Rows.RemoveAt(0);
                }
            }
            catch
            {
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }


        /// <summary>
        /// 读取表格到Table
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public DataSet ExcelToD_Data(string Path, bool hasheader = false)
        {
            string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";" + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataSet ds = null;
            try
            {
                //获取动态名称  
                //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等   
                DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                //包含excel中表名的字符串数组  
                string[] strTableNames = new string[dtSheetName.Rows.Count];
                for (int k = 0; k < dtSheetName.Rows.Count; k++)
                {
                    strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
                }
                if (strTableNames.Count() > 0)
                {
                    OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", strTableNames[1]), conn);
                    ds = new DataSet();
                    odda.Fill(ds, strTableNames[1]);
                }

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

                    //将表格第一行设置为标题
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        string columnname = "F" + (i + 1).ToString();
                        if (ds.Tables[0].Columns[i].ColumnName.Equals(columnname))
                        {
                            ds.Tables[0].Columns[i].ColumnName = ds.Tables[0].Rows[0][columnname].ToString();
                        }
                    }
                    ds.Tables[0].Rows.RemoveAt(0);
                }
            }
            catch
            {
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }

        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public DataTable CSVToTable(string filePath)
        {
            Encoding encoding = Encoding.Default;//
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            //StreamReader sr = new StreamReader(fs, encoding);
            string openid = string.Empty;
            try
            {
                //string fileContent = sr.ReadToEnd();
                //encoding = sr.CurrentEncoding;
                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine = null;
                string[] tableHead = null;
                //标示列数
                int columnCount = 0;
                //标示是否是读取的第一行
                bool IsFirst = true;
                //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    if (IsFirst == true)
                    {
                        tableHead = strLine.Split(',');
                        IsFirst = false;
                        columnCount = tableHead.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            DataColumn dc = new DataColumn(tableHead[i]);
                            if (!dt.Columns.Contains(dc.ToString()))
                            {
                                dt.Columns.Add(dc);
                            }
                            else
                            { 
                                throw new Exception("列名出现重复:" + dc.ToString());
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            columnCount = dt.Columns.Count;
                            aryLine = strLine.Split(',');
                            if (string.IsNullOrWhiteSpace(aryLine[0]))//每行首列为空, 不添加
                            { 
                                continue;
                            }
                            DataRow dr = dt.NewRow();
                            for (int j = 0; j < columnCount; j++)
                            {
                                dr[j] = aryLine[j].Replace("\"", "").Replace("\t", "");
                            }
                            dt.Rows.Add(dr);
                        }
                        catch(Exception ex)
                        {

                        }
                    }
                }
                if (aryLine != null && aryLine.Length > 0)
                {
                    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sr.Close();
                fs.Close();
            }
            return dt;
        }

        /// <summary>
        /// 写入表格
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="oldds"></param>
        public void DSToExcel(string Path, DataSet oldds)
        {
            //先得到汇总EXCEL的DataSet 主要目的是获得EXCEL在DataSet中的结构 
            string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Path + ";Extended Properties=Excel 8.0";
            OleDbConnection myConn = new OleDbConnection(strCon);
            string strCom = "select * from [Sheet1$]";
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);
            //QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。 
            builder.QuotePrefix = "[";     //获取insert语句中保留字符(起始位置) 
            builder.QuoteSuffix = "]"; //获取insert语句中保留字符(结束位置) 
            DataSet newds = new DataSet();
            myCommand.Fill(newds, "Table1");
            for (int i = 0; i < oldds.Tables[0].Rows.Count; i++)
            {
                //在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。
                //在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added 
                DataRow nrow = oldds.Tables["Table1"].NewRow();
                for (int j = 0; j < newds.Tables[0].Columns.Count; j++)
                {
                    nrow[j] = oldds.Tables[0].Rows[i][j];
                }
                newds.Tables["Table1"].Rows.Add(nrow);
            }
            myCommand.Update(newds, "Table1");
            myConn.Close();
        }
        /// <summary>
        /// datatable 转EXCEL
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool DsSaveToExcel(string path, DataTable dt)
        {
            bool result = false;
            try
            {
                String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
                //实例化一个Oledbconnection类(实现了IDisposable,要using)
                using (OleDbConnection ole_conn = new OleDbConnection(sConnectionString))
                {
                    ole_conn.Open();
                    using (OleDbCommand ole_cmd = ole_conn.CreateCommand())
                    {
                        try
                        {
                            ole_cmd.CommandText = "CREATE TABLE 中心铺货 ([配送中心ID] Int,[门店ID] Int,[货品ID] Int,[数量] Int)";
                            ole_cmd.ExecuteNonQuery();
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                ole_cmd.CommandText = string.Format("insert into 中心铺货([配送中心ID],[门店ID],[货品ID],[数量])values(4450,19176,{0},{1})", dt.Rows[i]["货品ID"].ToString(), dt.Rows[i]["数量"].ToString());
                                ole_cmd.ExecuteNonQuery();
                            }
                        }
                        catch { }
                        result = true;
                    }
                    ole_conn.Close();
                }
            }
            catch { }
            return result;
        }
        /// <summary>
        /// datatable 转EXCEL
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool DsSaveToExcelForJD(string path, DataTable dt)
        {
            bool result = false;
            String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
            //实例化一个Oledbconnection类(实现了IDisposable,要using)
            using (OleDbConnection ole_conn = new OleDbConnection(sConnectionString))
            {
                ole_conn.Open();
                using (OleDbCommand ole_cmd = ole_conn.CreateCommand())
                {
                    try
                    {
                        ole_cmd.CommandText = "CREATE TABLE 商品图列表 ([地址] varchar(200),[京东编码] varchar(100),[商家编码] varchar(100))";
                        ole_cmd.ExecuteNonQuery();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            ole_cmd.CommandText = string.Format("insert into 商品图列表([地址],[京东编码],[商家编码])values('{0}','{1}','{2}')", dt.Rows[i]["地址"].ToString(), dt.Rows[i]["京东编码"].ToString(), dt.Rows[i]["商家编码"].ToString());
                            ole_cmd.ExecuteNonQuery();
                        }
                    }
                    catch { }
                    result = true;
                }
                ole_conn.Close();
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="dataTable"></param>
        public void SaveAsXlS(string fileName, DataTable dataTable)
        {
            System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
            DataSet set = new DataSet();

            dataTable.TableName = fileName;
            set.Tables.Add(dataTable.Copy());

            grid.HeaderStyle.Font.Bold = true;
            grid.DataSource = set;
            grid.DataMember = set.Tables[dataTable.TableName].TableName;
            grid.DataBind();

            using (StreamWriter sw = new StreamWriter(fileName))
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    grid.RenderControl(hw);
                }
            }

        }

        /// <summary>
        /// 将DataTable中数据写入到CSV文件中
        /// </summary>
        /// <param name="dt">提供保存数据的DataTable</param>
        /// <param name="fileName">CSV的文件路径</param>
        public static void SaveCSV(DataTable dt, string fullPath)
        {
            FileInfo fi = new FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            string data = "";
            //写出列名称
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data += dt.Columns[i].ColumnName.ToString();
                if (i < dt.Columns.Count - 1)
                {
                    data += ",";
                }
            }
            sw.WriteLine(data);
            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string str = dt.Rows[i][j].ToString();
                    str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
                    if (str.Contains(',') || str.Contains('"')
                        || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
                    {
                        str = string.Format("\"{0}\"", str);
                    }

                    data += str;
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 下载网页图片至指定位置
        /// </summary>
        /// <param name="Imgurl"></param>
        /// <param name="pathname">绝对路径</param>
        /// <param name="filename">文件名</param>
        public static void downloadImage(string Imgurl, string pathname, string filename)
        {
            WebRequest request = WebRequest.Create(Imgurl);
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();
            if (!System.IO.Directory.Exists(pathname))
            {
                System.IO.Directory.CreateDirectory(pathname);
            }
            FileStream writer = new FileStream(pathname + filename, FileMode.OpenOrCreate, FileAccess.Write);
            byte[] buff = new byte[512];
            int c = 0; //实际读取的字节数
            while ((c = reader.Read(buff, 0, buff.Length)) > 0)
            {
                writer.Write(buff, 0, c);
            }
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            response.Close();
        }

        public static void downloadImage(string Imgurl, Dictionary<string, string> keyValues)
        {
            foreach (var item in keyValues)
            {
                try
                {
                    Thread.Sleep(2);
                    WebRequest request = WebRequest.Create(Imgurl);
                    WebResponse response = request.GetResponse();
                    Stream reader = response.GetResponseStream();
                    if (!Directory.Exists(item.Value))
                    {
                        Directory.CreateDirectory(item.Value);
                    }

                    FileStream writer = new FileStream(item.Value + item.Key, FileMode.OpenOrCreate, FileAccess.Write);
                    byte[] buff = new byte[512];
                    int c = 0; //实际读取的字节数
                    while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                    {
                        writer.Write(buff, 0, c);
                    }
                    writer.Close();
                    writer.Dispose();
                    reader.Close();
                    reader.Dispose();
                    response.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("***************保存图片报错了,错误{0}****************", ex.Message);
                }
            }
        }


        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);

            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return true;
            }
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
        /// <summary>
        /// 删除文件夹和文件
        /// </summary>
        /// <param name="directoryPath">文件路径</param>
        /// <param name="fileName">文件名称</param>
        public static void DeleteDirectory(string directoryPath, string fileName)
        {

            //删除文件
            for (int i = 0; i < Directory.GetFiles(directoryPath).ToList().Count; i++)
            {
                if (Directory.GetFiles(directoryPath)[i] == fileName)
                {
                    File.Delete(fileName);
                }
            }

            //删除文件夹
            for (int i = 0; i < Directory.GetDirectories(directoryPath).ToList().Count; i++)
            {
                if (Directory.GetDirectories(directoryPath)[i] == fileName)
                {
                    Directory.Delete(fileName, true);
                }
            }
        }




        /// <summary>
        /// Resize image with a directory as source
        /// </summary>
        /// <param name="OriginalFileLocation">Image location</param>
        /// <param name="heigth">new height</param>
        /// <param name="width">new width</param>
        /// <param name="keepAspectRatio">keep the aspect ratio</param>
        /// <param name="getCenter">return the center bit of the image</param>
        /// <returns>image with new dimentions</returns>
        public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
        {
            int newheigth = heigth;
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (keepAspectRatio || getCenter)
            {
                int bmpY = 0;
                double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
                if (getCenter)
                {
                    bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
                    Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
                                                                                                                                 //System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY);
                    Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
                    FullsizeImage.Dispose();//clear the original image
                    using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                    {
                        Graphics cutImg = Graphics.FromImage(tempImg);//              set the file to save the new image to.
                        cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
                        FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
                        orImg.Dispose();
                        cutImg.Dispose();
                        return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
                    }
                }
                else newheigth = (int)(FullsizeImage.Height / resize);//  set the new heigth of the current image
            }//return the image resized to the given heigth and width
            return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
        }


        /// <summary>
        /// Resize image with a directory as source
        /// </summary>
        /// <param name="OriginalFileLocation">Image location</param>
        /// <param name="heigth">new height</param>
        /// <param name="width">new width</param>
        /// <returns>image with new dimentions</returns>
        public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width)
        {
            return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false);
        }

        /// <summary>
        /// Resize image with a directory as source
        /// </summary>
        /// <param name="OriginalFileLocation">Image location</param>
        /// <param name="heigth">new height</param>
        /// <param name="width">new width</param>
        /// <param name="keepAspectRatio">keep the aspect ratio</param>
        /// <returns>image with new dimentions</returns>
        public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio)
        {
            return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false);
        }

        /// <summary>  
        /// 导出速度最快  
        /// </summary>  
        /// <param name="list"><列名,数据></param>  
        /// <param name="filepath"></param>  
        /// <returns></returns>  
        public bool NewExport(List<DictionaryEntry> list, string filepath,out string ErrorMsg)
        {
            bool bSuccess = true;
            ErrorMsg = string.Empty;
            Microsoft.Office.Interop.Excel.Application appexcel = new Microsoft.Office.Interop.Excel.Application();
            System.Reflection.Missing miss = System.Reflection.Missing.Value;
            appexcel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workbookdata = null;
            Microsoft.Office.Interop.Excel.Worksheet worksheetdata = null;
            Microsoft.Office.Interop.Excel.Range rangedata;

            workbookdata = appexcel.Workbooks.Add();

            //设置对象不可见  
            appexcel.Visible = false;
            appexcel.DisplayAlerts = false;
            try
            {
                foreach (var lv in list)
                {
                    var keys = lv.Key as List<string>;
                    var values = lv.Value as List<IList<object>>;
                    worksheetdata = (Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets.Add(miss, workbookdata.ActiveSheet);

                    for (int i = 0; i < keys.Count - 1; i++)
                    {
                        //给工作表赋名称  
                        worksheetdata.Name = keys[0];//列名的第一个数据位表名  
                        worksheetdata.Cells[1, i + 1] = keys[i + 1];
                    }

                    //因为第一行已经写了表头,所以所有数据都应该从a2开始  
                    rangedata = worksheetdata.get_Range("a2", miss);
                    Microsoft.Office.Interop.Excel.Range xlrang = null;

                    //irowcount为实际行数,最大行  
                    int irowcount = values.Count;
                    int iparstedrow = 0, icurrsize = 0;

                    //ieachsize为每次写行的数值,可以自己设置  
                    int ieachsize = 10000;

                    //icolumnaccount为实际列数,最大列数  
                    int icolumnaccount = keys.Count - 1;

                    //在内存中声明一个ieachsize×icolumnaccount的数组,ieachsize是每次最大存储的行数,icolumnaccount就是存储的实际列数  
                    object[,] objval = new object[ieachsize, icolumnaccount];
                    icurrsize = ieachsize;

                    while (iparstedrow < irowcount)
                    {
                        if ((irowcount - iparstedrow) < ieachsize)
                            icurrsize = irowcount - iparstedrow;

                        //用for循环给数组赋值  
                        for (int i = 0; i < icurrsize; i++)
                        {
                            for (int j = 0; j < icolumnaccount; j++)
                            {
                                var v = values[i + iparstedrow][j];
                                objval[i, j] = v != null ? v.ToString() : "";
                            }
                        }
                        string X = "A" + ((int)(iparstedrow + 2)).ToString();
                        string col = "";
                        if (icolumnaccount <= 26)
                        {
                            col = ((char)('A' + icolumnaccount - 1)).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();
                        }
                        else
                        {
                            col = ((char)('A' + (icolumnaccount / 26 - 1))).ToString() + ((char)('A' + (icolumnaccount % 26 - 1))).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();
                        }
                        xlrang = worksheetdata.get_Range(X, col);
                        xlrang.NumberFormat = "@";
                        // 调用range的value2属性,把内存中的值赋给excel  
                        xlrang.Value2 = objval;
                        iparstedrow = iparstedrow + icurrsize;
                    }
                }
                ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet1"]).Delete();
                ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet2"]).Delete();
                ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet3"]).Delete();
                //保存工作表  
                workbookdata.SaveAs(filepath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                workbookdata.Close(false, miss, miss);
                appexcel.Workbooks.Close();
                appexcel.Quit();

                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbookdata);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel.Workbooks);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel);
                GC.Collect();
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
                bSuccess = false;
            }
            finally
            {
                if (appexcel != null)
                {
                    //ExcelImportHelper.KillSpecialExcel(appexcel);
                }
            }
            return bSuccess;
        }

        public static bool ExportToExcel(DataTable table, string saveFileName,string columnNames)
        {

            bool fileSaved = false;

            //ExcelApp xlApp = new ExcelApp();

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return fileSaved;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1

            long rows = table.Rows.Count;

            /*下边注释的两行代码当数据行数超过行时,出现异常:异常来自HRESULT:0x800A03EC。因为:Excel 2003每个sheet只支持最大行数据

            //Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count+2, gridview.Columns.View.VisibleColumns.Count+1]);

            //fchR.Value2 = datas;*/

            string[] columnNameList = new string[] { };
            List<int> numberFormat = new List<int>();//内容增加防科学计数法
            int diyNameCount = 0;
            if (!string.IsNullOrWhiteSpace(columnNames)) {
                columnNameList = columnNames.Split(',');
                diyNameCount = columnNameList.Count();
            }

            if (rows > 65535)
            {

                long pageRows = 60000;//定义每页显示的行数,行数必须小于

                int scount = (int)(rows / pageRows);

                if (scount * pageRows < table.Rows.Count)//当总行数不被pageRows整除时,经过四舍五入可能页数不准
                {
                    scount = scount + 1;
                }

                for (int sc = 1; sc <= scount; sc++)
                {
                    if (sc > 1)
                    {
                        object missing = System.Reflection.Missing.Value;

                        worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(

                        missing, missing, missing, missing);//添加一个sheet

                    }

                    else
                    {
                        worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[sc];//取得sheet1
                    }

                    string[,] datas = new string[pageRows + 1, table.Columns.Count + 1];

                    for (int i = 0; i < table.Columns.Count; i++) //写入字段
                    {
                        if(i < diyNameCount)
                        {
                            string headerName = columnNameList[i];
                            if (headerName.EndsWith("numberformat"))
                            {
                                numberFormat.Add(i);
                                datas[0, i] = headerName.Replace("numberformat","");
                            }
                        }
                        else
                        {
                            datas[0, i] = table.Columns[i].Caption;
                        }
                    }

                    Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]];
                    range.Interior.ColorIndex = 15;//15代表灰色
                    range.Font.Bold = true;
                    range.Font.Size = 9;

                    int init = int.Parse(((sc - 1) * pageRows).ToString());
                    int r = 0;
                    int index = 0;
                    int result;

                    if (pageRows * sc >= table.Rows.Count)
                    {
                        result = table.Rows.Count;
                    }
                    else
                    {
                        result = int.Parse((pageRows * sc).ToString());
                    }
                    for (r = init; r < result; r++)
                    {
                        index = index + 1;
                        for (int i = 0; i < table.Columns.Count; i++)
                        {
                            if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal)
                                || table.Columns[i].DataType == typeof(Double) || table.Columns[i].DataType == typeof(Int64)
                                || table.Columns[i].DataType == typeof(DateTime))
                            {
                                object obj = table.Rows[r][table.Columns[i].ColumnName];
                                if (numberFormat.Contains(i))
                                {
                                    datas[index, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                                }
                                else
                                {
                                    datas[index, i] = obj == null ? "" : obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                                }
                            }
                        }
                    }

                    Microsoft.Office.Interop.Excel.Range fchR = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[index + 2, table.Columns.Count + 1]];

                    fchR.Value2 = datas;
                    worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。

                    range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[index + 1, table.Columns.Count]];

                    //15代表灰色

                    range.Font.Size = 9;
                    range.RowHeight = 14.25;
                    range.Borders.LineStyle = 1;
                    range.HorizontalAlignment = 1;

                }

            }
            else
            {

                string[,] datas = new string[table.Rows.Count + 2, table.Columns.Count + 1];
                for (int i = 0; i < table.Columns.Count; i++) //写入字段     
                {
                    if (i < diyNameCount)
                    {
                        string headerName = columnNameList[i];
                        if (headerName.EndsWith("numberformat"))
                        {
                            numberFormat.Add(i);
                        }
                        datas[0, i] = headerName.Replace("numberformat", "");
                    }
                    else
                    {
                        datas[0, i] = table.Columns[i].Caption;
                    }
                }

                Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]];
                range.Interior.ColorIndex = 15;//15代表灰色
                range.Font.Bold = true;
                range.Font.Size = 9;

                int r = 0;
                for (r = 0; r < table.Rows.Count; r++)
                {
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal) 
                            || table.Columns[i].DataType == typeof(Double) || table.Columns[i].DataType == typeof(Int64) 
                            || table.Columns[i].DataType == typeof(DateTime))
                        {
                            object obj = table.Rows[r][table.Columns[i].ColumnName];
                            if(numberFormat.Contains(i))
                            {
                                datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                            }
                            else
                            {
                                datas[r + 1, i] = obj == null ? "" : obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                            }

                        }
                    }
                }

                Microsoft.Office.Interop.Excel.Range fchR = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 1]];

                fchR.Value2 = datas;

                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。

                range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1, table.Columns.Count]];

                //15代表灰色

                range.Font.Size = 9;
                range.RowHeight = 14.25;
                range.Borders.LineStyle = 1;
                range.HorizontalAlignment = 1;
            }

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    string dir = System.AppDomain.CurrentDomain.BaseDirectory + "outfile\\";

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    workbook.SaveCopyAs(dir + saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                }
            }
            else
            {
                fileSaved = false;
            }

            xlApp.Quit();

            GC.Collect();//强行销毁 
            return fileSaved;
        }

    }
}
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf( ".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf( ".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow( 0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return -1;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf( ".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf( ".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt( 0);
}
}
else
{
sheet = workbook.GetSheetAt( 0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow( 0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for ( int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for ( int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null       
DataRow dataRow = data.NewRow();
for ( int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine( "Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
Dispose( true);
GC.SuppressFinalize( this);
}
protected virtual void Dispose(bool disposing)
{
if (! this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}