zoukankan      html  css  js  c++  java
  • [置顶] 将数据导出到excel文件的操作类(用法大全)

    [             /// <summary>   
    1.    /// Excel操作类   
    2.    /// </summary>   
    3.    /// Microsoft Excel 11.0 Object Library   
    4.    public class ExcelHelper  
    5.    {  
    6.        #region 数据导出至Excel文件   
    7.        /// </summary>    
    8.        /// 导出Excel文件,自动返回可下载的文件流    
    9.        /// </summary>    
    10.        public static void DataTable1Excel(System.Data.DataTable dtData)  
    11.        {  
    12.            GridView gvExport = null;  
    13.            HttpContext curContext = HttpContext.Current;  
    14.            StringWriter strWriter = null;  
    15.            HtmlTextWriter htmlWriter = null;  
    16.            if (dtData != null)  
    17.            {  
    18.                curContext.Response.ContentType = "application/vnd.ms-excel";  
    19.                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");  
    20.                curContext.Response.Charset = "utf-8";  
    21.   
    22.                strWriter = new StringWriter();  
    23.                htmlWriter = new HtmlTextWriter(strWriter);  
    24.                gvExport = new GridView();  
    25.                gvExport.DataSource = dtData.DefaultView;  
    26.                gvExport.AllowPaging = false;  
    27.                gvExport.DataBind();  
    28.                gvExport.RenderControl(htmlWriter);  
    29.   
    30.                curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString());  
    31.                curContext.Response.End();  
    32.            }  
    33.        }  
    34.   
    35.        /// <summary>   
    36.        /// 导出Excel文件,转换为可读模式   
    37.        /// </summary>   
    38.        public static void DataTable2Excel(System.Data.DataTable dtData)  
    39.        {  
    40.            DataGrid dgExport = null;  
    41.            HttpContext curContext = HttpContext.Current;  
    42.            StringWriter strWriter = null;  
    43.            HtmlTextWriter htmlWriter = null;  
    44.   
    45.            if (dtData != null)  
    46.            {  
    47.                curContext.Response.ContentType = "application/vnd.ms-excel";  
    48.                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;  
    49.                curContext.Response.Charset = "";  
    50.                strWriter = new StringWriter();  
    51.                htmlWriter = new HtmlTextWriter(strWriter);  
    52.                dgExport = new DataGrid();  
    53.                dgExport.DataSource = dtData.DefaultView;  
    54.                dgExport.AllowPaging = false;  
    55.                dgExport.DataBind();  
    56.                dgExport.RenderControl(htmlWriter);  
    57.                curContext.Response.Write(strWriter.ToString());  
    58.                curContext.Response.End();  
    59.            }  
    60.        }  
    61.   
    62.        /// <summary>   
    63.        /// 导出Excel文件,并自定义文件名   
    64.        /// </summary>   
    65.        public static void DataTable3Excel(System.Data.DataTable dtData, String FileName)  
    66.        {  
    67.            GridView dgExport = null;  
    68.            HttpContext curContext = HttpContext.Current;  
    69.            StringWriter strWriter = null;  
    70.            HtmlTextWriter htmlWriter = null;  
    71.   
    72.            if (dtData != null)  
    73.            {  
    74.                HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);  
    75.                curContext.Response.AddHeader("content-disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");  
    76.                curContext.Response.ContentType = "application nd.ms-excel";  
    77.                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;  
    78.                curContext.Response.Charset = "GB2312";  
    79.                strWriter = new StringWriter();  
    80.                htmlWriter = new HtmlTextWriter(strWriter);  
    81.                dgExport = new GridView();  
    82.                dgExport.DataSource = dtData.DefaultView;  
    83.                dgExport.AllowPaging = false;  
    84.                dgExport.DataBind();  
    85.                dgExport.RenderControl(htmlWriter);  
    86.                curContext.Response.Write(strWriter.ToString());  
    87.                curContext.Response.End();  
    88.            }  
    89.        }  
    90.   
    91.        /// <summary>   
    92.        /// 将数据导出至Excel文件   
    93.        /// </summary>   
    94.        /// <param name="Table">DataTable对象</param>   
    95.        /// <param name="ExcelFilePath">Excel文件路径</param>   
    96.        public static bool OutputToExcel(DataTable Table, string ExcelFilePath)  
    97.        {  
    98.            if (File.Exists(ExcelFilePath))  
    99.            {  
    100.                throw new Exception("该文件已经存在!");  
    101.            }  
    102.   
    103.            if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))  
    104.            {  
    105.                Table.TableName = "Sheet1";  
    106.            }  
    107.   
    108.            //数据表的列数   
    109.            int ColCount = Table.Columns.Count;  
    110.   
    111.            //用于记数,实例化参数时的序号   
    112.            int i = 0;  
    113.   
    114.            //创建参数   
    115.            OleDbParameter[] para = new OleDbParameter[ColCount];  
    116.   
    117.            //创建表结构的SQL语句   
    118.            string TableStructStr = @"Create Table " + Table.TableName + "(";  
    119.   
    120.            //连接字符串   
    121.            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";  
    122.            OleDbConnection objConn = new OleDbConnection(connString);  
    123.   
    124.            //创建表结构   
    125.            OleDbCommand objCmd = new OleDbCommand();  
    126.   
    127.            //数据类型集合   
    128.            ArrayList DataTypeList = new ArrayList();  
    129.            DataTypeList.Add("System.Decimal");  
    130.            DataTypeList.Add("System.Double");  
    131.            DataTypeList.Add("System.Int16");  
    132.            DataTypeList.Add("System.Int32");  
    133.            DataTypeList.Add("System.Int64");  
    134.            DataTypeList.Add("System.Single");  
    135.   
    136.            //遍历数据表的所有列,用于创建表结构   
    137.            foreach (DataColumn col in Table.Columns)  
    138.            {  
    139.                //如果列属于数字列,则设置该列的数据类型为double   
    140.                if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0)  
    141.                {  
    142.                    para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double);  
    143.                    objCmd.Parameters.Add(para[i]);  
    144.   
    145.                    //如果是最后一列   
    146.                    if (i + 1 == ColCount)  
    147.                    {  
    148.                        TableStructStr += col.ColumnName + " double)";  
    149.                    }  
    150.                    else  
    151.                    {  
    152.                        TableStructStr += col.ColumnName + " double,";  
    153.                    }  
    154.                }  
    155.                else  
    156.                {  
    157.                    para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar);  
    158.                    objCmd.Parameters.Add(para[i]);  
    159.   
    160.                    //如果是最后一列   
    161.                    if (i + 1 == ColCount)  
    162.                    {  
    163.                        TableStructStr += col.ColumnName + " varchar)";  
    164.                    }  
    165.                    else  
    166.                    {  
    167.                        TableStructStr += col.ColumnName + " varchar,";  
    168.                    }  
    169.                }  
    170.                i++;  
    171.            }  
    172.   
    173.            //创建Excel文件及文件结构   
    174.            try  
    175.            {  
    176.                objCmd.Connection = objConn;  
    177.                objCmd.CommandText = TableStructStr;  
    178.   
    179.                if (objConn.State == ConnectionState.Closed)  
    180.                {  
    181.                    objConn.Open();  
    182.                }  
    183.                objCmd.ExecuteNonQuery();  
    184.            }  
    185.            catch (Exception exp)  
    186.            {  
    187.                throw exp;  
    188.            }  
    189.   
    190.            //插入记录的SQL语句   
    191.            string InsertSql_1 = "Insert into " + Table.TableName + " (";  
    192.            string InsertSql_2 = " Values (";  
    193.            string InsertSql = "";  
    194.   
    195.            //遍历所有列,用于插入记录,在此创建插入记录的SQL语句   
    196.            for (int colID = 0; colID < ColCount; colID++)  
    197.            {  
    198.                if (colID + 1 == ColCount)  //最后一列   
    199.                {  
    200.                    InsertSql_1 += Table.Columns[colID].ColumnName + ")";  
    201.                    InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")";  
    202.                }  
    203.                else  
    204.                {  
    205.                    InsertSql_1 += Table.Columns[colID].ColumnName + ",";  
    206.                    InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ",";  
    207.                }  
    208.            }  
    209.   
    210.            InsertSql = InsertSql_1 + InsertSql_2;  
    211.   
    212.            //遍历数据表的所有数据行   
    213.            for (int rowID = 0; rowID < Table.Rows.Count; rowID++)  
    214.            {  
    215.                for (int colID = 0; colID < ColCount; colID++)  
    216.                {  
    217.                    if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")  
    218.                    {  
    219.                        para[colID].Value = 0;  
    220.                    }  
    221.                    else  
    222.                    {  
    223.                        para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();  
    224.                    }  
    225.                }  
    226.                try  
    227.                {  
    228.                    objCmd.CommandText = InsertSql;  
    229.                    objCmd.ExecuteNonQuery();  
    230.                }  
    231.                catch (Exception exp)  
    232.                {  
    233.                    string str = exp.Message;  
    234.                }  
    235.            }  
    236.            try  
    237.            {  
    238.                if (objConn.State == ConnectionState.Open)  
    239.                {  
    240.                    objConn.Close();  
    241.                }  
    242.            }  
    243.            catch (Exception exp)  
    244.            {  
    245.                throw exp;  
    246.            }  
    247.            return true;  
    248.        }  
    249.   
    250.        /// <summary>   
    251.        /// 将数据导出至Excel文件   
    252.        /// </summary>   
    253.        /// <param name="Table">DataTable对象</param>   
    254.        /// <param name="Columns">要导出的数据列集合</param>   
    255.        /// <param name="ExcelFilePath">Excel文件路径</param>   
    256.        public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath)  
    257.        {  
    258.            if (File.Exists(ExcelFilePath))  
    259.            {  
    260.                throw new Exception("该文件已经存在!");  
    261.            }  
    262.   
    263.            //如果数据列数大于表的列数,取数据表的所有列   
    264.            if (Columns.Count > Table.Columns.Count)  
    265.            {  
    266.                for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++)  
    267.                {  
    268.                    Columns.RemoveAt(s);   //移除数据表列数后的所有列   
    269.                }  
    270.            }  
    271.   
    272.            //遍历所有的数据列,如果有数据列的数据类型不是 DataColumn,则将它移除   
    273.            DataColumn column = new DataColumn();  
    274.            for (int j = 0; j < Columns.Count; j++)  
    275.            {  
    276.                try  
    277.                {  
    278.                    column = (DataColumn)Columns[j];  
    279.                }  
    280.                catch (Exception)  
    281.                {  
    282.                    Columns.RemoveAt(j);  
    283.                }  
    284.            }  
    285.            if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))  
    286.            {  
    287.                Table.TableName = "Sheet1";  
    288.            }  
    289.   
    290.            //数据表的列数   
    291.            int ColCount = Columns.Count;  
    292.   
    293.            //创建参数   
    294.            OleDbParameter[] para = new OleDbParameter[ColCount];  
    295.   
    296.            //创建表结构的SQL语句   
    297.            string TableStructStr = @"Create Table " + Table.TableName + "(";  
    298.   
    299.            //连接字符串   
    300.            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";  
    301.            OleDbConnection objConn = new OleDbConnection(connString);  
    302.   
    303.            //创建表结构   
    304.            OleDbCommand objCmd = new OleDbCommand();  
    305.   
    306.            //数据类型集合   
    307.            ArrayList DataTypeList = new ArrayList();  
    308.            DataTypeList.Add("System.Decimal");  
    309.            DataTypeList.Add("System.Double");  
    310.            DataTypeList.Add("System.Int16");  
    311.            DataTypeList.Add("System.Int32");  
    312.            DataTypeList.Add("System.Int64");  
    313.            DataTypeList.Add("System.Single");  
    314.   
    315.            DataColumn col = new DataColumn();  
    316.   
    317.            //遍历数据表的所有列,用于创建表结构   
    318.            for (int k = 0; k < ColCount; k++)  
    319.            {  
    320.                col = (DataColumn)Columns[k];  
    321.   
    322.                //列的数据类型是数字型   
    323.                if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0)  
    324.                {  
    325.                    para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double);  
    326.                    objCmd.Parameters.Add(para[k]);  
    327.   
    328.                    //如果是最后一列   
    329.                    if (k + 1 == ColCount)  
    330.                    {  
    331.                        TableStructStr += col.Caption.Trim() + " Double)";  
    332.                    }  
    333.                    else  
    334.                    {  
    335.                        TableStructStr += col.Caption.Trim() + " Double,";  
    336.                    }  
    337.                }  
    338.                else  
    339.                {  
    340.                    para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar);  
    341.                    objCmd.Parameters.Add(para[k]);  
    342.   
    343.                    //如果是最后一列   
    344.                    if (k + 1 == ColCount)  
    345.                    {  
    346.                        TableStructStr += col.Caption.Trim() + " VarChar)";  
    347.                    }  
    348.                    else  
    349.                    {  
    350.                        TableStructStr += col.Caption.Trim() + " VarChar,";  
    351.                    }  
    352.                }  
    353.            }  
    354.   
    355.            //创建Excel文件及文件结构   
    356.            try  
    357.            {  
    358.                objCmd.Connection = objConn;  
    359.                objCmd.CommandText = TableStructStr;  
    360.   
    361.                if (objConn.State == ConnectionState.Closed)  
    362.                {  
    363.                    objConn.Open();  
    364.                }  
    365.                objCmd.ExecuteNonQuery();  
    366.            }  
    367.            catch (Exception exp)  
    368.            {  
    369.                throw exp;  
    370.            }  
    371.   
    372.            //插入记录的SQL语句   
    373.            string InsertSql_1 = "Insert into " + Table.TableName + " (";  
    374.            string InsertSql_2 = " Values (";  
    375.            string InsertSql = "";  
    376.   
    377.            //遍历所有列,用于插入记录,在此创建插入记录的SQL语句   
    378.            for (int colID = 0; colID < ColCount; colID++)  
    379.            {  
    380.                if (colID + 1 == ColCount)  //最后一列   
    381.                {  
    382.                    InsertSql_1 += Columns[colID].ToString().Trim() + ")";  
    383.                    InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")";  
    384.                }  
    385.                else  
    386.                {  
    387.                    InsertSql_1 += Columns[colID].ToString().Trim() + ",";  
    388.                    InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ",";  
    389.                }  
    390.            }  
    391.   
    392.            InsertSql = InsertSql_1 + InsertSql_2;  
    393.   
    394.            //遍历数据表的所有数据行   
    395.            DataColumn DataCol = new DataColumn();  
    396.            for (int rowID = 0; rowID < Table.Rows.Count; rowID++)  
    397.            {  
    398.                for (int colID = 0; colID < ColCount; colID++)  
    399.                {  
    400.                    //因为列不连续,所以在取得单元格时不能用行列编号,列需得用列的名称   
    401.                    DataCol = (DataColumn)Columns[colID];  
    402.                    if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "")  
    403.                    {  
    404.                        para[colID].Value = 0;  
    405.                    }  
    406.                    else  
    407.                    {  
    408.                        para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim();  
    409.                    }  
    410.                }  
    411.                try  
    412.                {  
    413.                    objCmd.CommandText = InsertSql;  
    414.                    objCmd.ExecuteNonQuery();  
    415.                }  
    416.                catch (Exception exp)  
    417.                {  
    418.                    string str = exp.Message;  
    419.                }  
    420.            }  
    421.            try  
    422.            {  
    423.                if (objConn.State == ConnectionState.Open)  
    424.                {  
    425.                    objConn.Close();  
    426.                }  
    427.            }  
    428.            catch (Exception exp)  
    429.            {  
    430.                throw exp;  
    431.            }  
    432.            return true;  
    433.        }  
    434.        #endregion   
    435.   
    436.        /// <summary>   
    437.        /// 获取Excel文件数据表列表   
    438.        /// </summary>   
    439.        public static ArrayList GetExcelTables(string ExcelFileName)  
    440.        {  
    441.            DataTable dt = new DataTable();  
    442.            ArrayList TablesList = new ArrayList();  
    443.            if (File.Exists(ExcelFileName))  
    444.            {  
    445.                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))  
    446.                {  
    447.                    try  
    448.                    {  
    449.                        conn.Open();  
    450.                        dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { nullnullnull"TABLE" });  
    451.                    }  
    452.                    catch (Exception exp)  
    453.                    {  
    454.                        throw exp;  
    455.                    }  
    456.   
    457.                    //获取数据表个数   
    458.                    int tablecount = dt.Rows.Count;  
    459.                    for (int i = 0; i < tablecount; i++)  
    460.                    {  
    461.                        string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');  
    462.                        if (TablesList.IndexOf(tablename) < 0)  
    463.                        {  
    464.                            TablesList.Add(tablename);  
    465.                        }  
    466.                    }  
    467.                }  
    468.            }  
    469.            return TablesList;  
    470.        }  
    471.   
    472.        /// <summary>   
    473.        /// 将Excel文件导出至DataTable(第一行作为表头)   
    474.        /// </summary>   
    475.        /// <param name="ExcelFilePath">Excel文件路径</param>   
    476.        /// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param>   
    477.        public static DataTable InputFromExcel(string ExcelFilePath, string TableName)  
    478.        {  
    479.            if (!File.Exists(ExcelFilePath))  
    480.            {  
    481.                throw new Exception("Excel文件不存在!");  
    482.            }  
    483.   
    484.            //如果数据表名不存在,则数据表名为Excel文件的第一个数据表   
    485.            ArrayList TableList = new ArrayList();  
    486.            TableList = GetExcelTables(ExcelFilePath);  
    487.   
    488.            if (TableName.IndexOf(TableName) < 0)  
    489.            {  
    490.                TableName = TableList[0].ToString().Trim();  
    491.            }  
    492.   
    493.            DataTable table = new DataTable();  
    494.            OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0");  
    495.            OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);  
    496.            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);  
    497.   
    498.            try  
    499.            {  
    500.                if (dbcon.State == ConnectionState.Closed)  
    501.                {  
    502.                    dbcon.Open();  
    503.                }  
    504.                adapter.Fill(table);  
    505.            }  
    506.            catch (Exception exp)  
    507.            {  
    508.                throw exp;  
    509.            }  
    510.            finally  
    511.            {  
    512.                if (dbcon.State == ConnectionState.Open)  
    513.                {  
    514.                    dbcon.Close();  
    515.                }  
    516.            }  
    517.            return table;  
    518.        }  
    519.   
    520.        /// <summary>   
    521.        /// 获取Excel文件指定数据表的数据列表   
    522.        /// </summary>   
    523.        /// <param name="ExcelFileName">Excel文件名</param>   
    524.        /// <param name="TableName">数据表名</param>   
    525.        public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName)  
    526.        {  
    527.            DataTable dt = new DataTable();  
    528.            ArrayList ColsList = new ArrayList();  
    529.            if (File.Exists(ExcelFileName))  
    530.            {  
    531.                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))  
    532.                {  
    533.                    conn.Open();  
    534.                    dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { nullnull, TableName, null });  
    535.   
    536.                    //获取列个数   
    537.                    int colcount = dt.Rows.Count;  
    538.                    for (int i = 0; i < colcount; i++)  
    539.                    {  
    540.                        string colname = dt.Rows[i]["Column_Name"].ToString().Trim();  
    541.                        ColsList.Add(colname);  
    542.                    }  
    543.                }  
    544.            }  
    545.            return ColsList;  
    546.        }  
    547.    }  
    548.   
    549.   
  • 相关阅读:
    对我影响最大的老师
    介绍自己
    JavaScript 时间特效 显示当前时间
    js 获取函数的所有参数名
    node.js 在函数内获取当前函数
    js 实现二叉排序树
    命令行下mysql的部分操作
    浅析js的函数的按值传递参数
    返回上一页时,保存恢复浏览记录(模拟返回不刷新)
    让mongodb执行js文件
  • 原文地址:https://www.cnblogs.com/wsq724439564/p/3258217.html
Copyright © 2011-2022 走看看