• ExcelHelper


    public class ExcelHelper
        {
            #region 数据导出至Excel文件
            /// </summary> 
            /// 导出Excel文件,自动返回可下载的文件流 
            /// </summary> 
            public static void DataTable1Excel(System.Data.DataTable dtData)
            {
                GridView gvExport = null;
                HttpContext curContext = HttpContext.Current;
                StringWriter strWriter = null;
                HtmlTextWriter htmlWriter = null;
                if (dtData != null)
                {
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    curContext.Response.Charset = "utf-8";
                    strWriter = new StringWriter();
                    htmlWriter = new HtmlTextWriter(strWriter);
                    gvExport = new GridView();
                    gvExport.DataSource = dtData.DefaultView;
                    gvExport.AllowPaging = false;
                    gvExport.DataBind();
                    gvExport.RenderControl(htmlWriter);
                    curContext.Response.Write("<meta http-equiv="Content-Type" content="text/html;charset=gb2312"/>" + strWriter.ToString());
                    curContext.Response.End();
                }
            }
    
            /// <summary>
            /// 导出Excel文件,转换为可读模式
            /// </summary>
            public static void DataTable2Excel(System.Data.DataTable dtData)
            {
                DataGrid dgExport = null;
                HttpContext curContext = HttpContext.Current;
                StringWriter strWriter = null;
                HtmlTextWriter htmlWriter = null;
    
                if (dtData != null)
                {
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    curContext.Response.Charset = "";
                    strWriter = new StringWriter();
                    htmlWriter = new HtmlTextWriter(strWriter);
                    dgExport = new DataGrid();
                    dgExport.DataSource = dtData.DefaultView;
                    dgExport.AllowPaging = false;
                    dgExport.DataBind();
                    dgExport.RenderControl(htmlWriter);
                    curContext.Response.Write(strWriter.ToString());
                    curContext.Response.End();
                }
            }
    
            /// <summary>
            /// 导出Excel文件,并自定义文件名
            /// </summary>
            public static void DataTable3Excel(System.Data.DataTable dtData, String FileName)
            {
                GridView dgExport = null;
                HttpContext curContext = HttpContext.Current;
                StringWriter strWriter = null;
                HtmlTextWriter htmlWriter = null;
    
                if (dtData != null)
                {
                    HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
                    curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                    curContext.Response.ContentType = "application nd.ms-excel";
                    curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    curContext.Response.Charset = "GB2312";
                    strWriter = new StringWriter();
                    htmlWriter = new HtmlTextWriter(strWriter);
                    dgExport = new GridView();
                    dgExport.DataSource = dtData.DefaultView;
                    dgExport.AllowPaging = false;
                    dgExport.DataBind();
                    dgExport.RenderControl(htmlWriter);
                    curContext.Response.Write(strWriter.ToString());
                    curContext.Response.End();
                }
            }
    
            /// <summary>
            /// 将数据导出至Excel文件
            /// </summary>
            /// <param name="Table">DataTable对象</param>
            /// <param name="ExcelFilePath">Excel文件路径</param>
            public static bool OutputToExcel(DataTable Table, string ExcelFilePath)
            {
                if (File.Exists(ExcelFilePath))
                {
                    throw new Exception("该文件已经存在!");
                }
    
                if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
                {
                    Table.TableName = "Sheet1";
                }
    
                //数据表的列数
                int ColCount = Table.Columns.Count;
    
                //用于记数,实例化参数时的序号
                int i = 0;
    
                //创建参数
                OleDbParameter[] para = new OleDbParameter[ColCount];
    
                //创建表结构的SQL语句
                string TableStructStr = @"Create Table " + Table.TableName + "(";
    
                //连接字符串
                string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
                OleDbConnection objConn = new OleDbConnection(connString);
    
                //创建表结构
                OleDbCommand objCmd = new OleDbCommand();
    
                //数据类型集合
                ArrayList DataTypeList = new ArrayList();
                DataTypeList.Add("System.Decimal");
                DataTypeList.Add("System.Double");
                DataTypeList.Add("System.Int16");
                DataTypeList.Add("System.Int32");
                DataTypeList.Add("System.Int64");
                DataTypeList.Add("System.Single");
    
                //遍历数据表的所有列,用于创建表结构
                foreach (DataColumn col in Table.Columns)
                {
                    //如果列属于数字列,则设置该列的数据类型为double
                    if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0)
                    {
                        para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double);
                        objCmd.Parameters.Add(para[i]);
    
                        //如果是最后一列
                        if (i + 1 == ColCount)
                        {
                            TableStructStr += col.ColumnName + " double)";
                        }
                        else
                        {
                            TableStructStr += col.ColumnName + " double,";
                        }
                    }
                    else
                    {
                        para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar);
                        objCmd.Parameters.Add(para[i]);
    
                        //如果是最后一列
                        if (i + 1 == ColCount)
                        {
                            TableStructStr += col.ColumnName + " varchar)";
                        }
                        else
                        {
                            TableStructStr += col.ColumnName + " varchar,";
                        }
                    }
                    i++;
                }
    
                //创建Excel文件及文件结构
                try
                {
                    objCmd.Connection = objConn;
                    objCmd.CommandText = TableStructStr;
    
                    if (objConn.State == ConnectionState.Closed)
                    {
                        objConn.Open();
                    }
                    objCmd.ExecuteNonQuery();
                }
                catch (Exception exp)
                {
                    throw exp;
                }
    
                //插入记录的SQL语句
                string InsertSql_1 = "Insert into " + Table.TableName + " (";
                string InsertSql_2 = " Values (";
                string InsertSql = "";
    
                //遍历所有列,用于插入记录,在此创建插入记录的SQL语句
                for (int colID = 0; colID < ColCount; colID++)
                {
                    if (colID + 1 == ColCount)  //最后一列
                    {
                        InsertSql_1 += Table.Columns[colID].ColumnName + ")";
                        InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")";
                    }
                    else
                    {
                        InsertSql_1 += Table.Columns[colID].ColumnName + ",";
                        InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ",";
                    }
                }
    
                InsertSql = InsertSql_1 + InsertSql_2;
    
                //遍历数据表的所有数据行
                for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
                {
                    for (int colID = 0; colID < ColCount; colID++)
                    {
                        if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")
                        {
                            para[colID].Value = 0;
                        }
                        else
                        {
                            para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();
                        }
                    }
                    try
                    {
                        objCmd.CommandText = InsertSql;
                        objCmd.ExecuteNonQuery();
                    }
                    catch (Exception exp)
                    {
                        string str = exp.Message;
                    }
                }
                try
                {
                    if (objConn.State == ConnectionState.Open)
                    {
                        objConn.Close();
                    }
                }
                catch (Exception exp)
                {
                    throw exp;
                }
                return true;
            }
    
            /// <summary>
            /// 将数据导出至Excel文件
            /// </summary>
            /// <param name="Table">DataTable对象</param>
            /// <param name="Columns">要导出的数据列集合</param>
            /// <param name="ExcelFilePath">Excel文件路径</param>
            public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath)
            {
                if (File.Exists(ExcelFilePath))
                {
                    throw new Exception("该文件已经存在!");
                }
    
                //如果数据列数大于表的列数,取数据表的所有列
                if (Columns.Count > Table.Columns.Count)
                {
                    for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++)
                    {
                        Columns.RemoveAt(s);   //移除数据表列数后的所有列
                    }
                }
    
                //遍历所有的数据列,如果有数据列的数据类型不是 DataColumn,则将它移除
                DataColumn column = new DataColumn();
                for (int j = 0; j < Columns.Count; j++)
                {
                    try
                    {
                        column = (DataColumn)Columns[j];
                    }
                    catch (Exception)
                    {
                        Columns.RemoveAt(j);
                    }
                }
                if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
                {
                    Table.TableName = "Sheet1";
                }
    
                //数据表的列数
                int ColCount = Columns.Count;
    
                //创建参数
                OleDbParameter[] para = new OleDbParameter[ColCount];
    
                //创建表结构的SQL语句
                string TableStructStr = @"Create Table " + Table.TableName + "(";
    
                //连接字符串
                string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
                OleDbConnection objConn = new OleDbConnection(connString);
    
                //创建表结构
                OleDbCommand objCmd = new OleDbCommand();
    
                //数据类型集合
                ArrayList DataTypeList = new ArrayList();
                DataTypeList.Add("System.Decimal");
                DataTypeList.Add("System.Double");
                DataTypeList.Add("System.Int16");
                DataTypeList.Add("System.Int32");
                DataTypeList.Add("System.Int64");
                DataTypeList.Add("System.Single");
    
                DataColumn col = new DataColumn();
    
                //遍历数据表的所有列,用于创建表结构
                for (int k = 0; k < ColCount; k++)
                {
                    col = (DataColumn)Columns[k];
    
                    //列的数据类型是数字型
                    if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0)
                    {
                        para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double);
                        objCmd.Parameters.Add(para[k]);
    
                        //如果是最后一列
                        if (k + 1 == ColCount)
                        {
                            TableStructStr += col.Caption.Trim() + " Double)";
                        }
                        else
                        {
                            TableStructStr += col.Caption.Trim() + " Double,";
                        }
                    }
                    else
                    {
                        para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar);
                        objCmd.Parameters.Add(para[k]);
    
                        //如果是最后一列
                        if (k + 1 == ColCount)
                        {
                            TableStructStr += col.Caption.Trim() + " VarChar)";
                        }
                        else
                        {
                            TableStructStr += col.Caption.Trim() + " VarChar,";
                        }
                    }
                }
    
                //创建Excel文件及文件结构
                try
                {
                    objCmd.Connection = objConn;
                    objCmd.CommandText = TableStructStr;
    
                    if (objConn.State == ConnectionState.Closed)
                    {
                        objConn.Open();
                    }
                    objCmd.ExecuteNonQuery();
                }
                catch (Exception exp)
                {
                    throw exp;
                }
    
                //插入记录的SQL语句
                string InsertSql_1 = "Insert into " + Table.TableName + " (";
                string InsertSql_2 = " Values (";
                string InsertSql = "";
    
                //遍历所有列,用于插入记录,在此创建插入记录的SQL语句
                for (int colID = 0; colID < ColCount; colID++)
                {
                    if (colID + 1 == ColCount)  //最后一列
                    {
                        InsertSql_1 += Columns[colID].ToString().Trim() + ")";
                        InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")";
                    }
                    else
                    {
                        InsertSql_1 += Columns[colID].ToString().Trim() + ",";
                        InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ",";
                    }
                }
    
                InsertSql = InsertSql_1 + InsertSql_2;
    
                //遍历数据表的所有数据行
                DataColumn DataCol = new DataColumn();
                for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
                {
                    for (int colID = 0; colID < ColCount; colID++)
                    {
                        //因为列不连续,所以在取得单元格时不能用行列编号,列需得用列的名称
                        DataCol = (DataColumn)Columns[colID];
                        if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "")
                        {
                            para[colID].Value = 0;
                        }
                        else
                        {
                            para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim();
                        }
                    }
                    try
                    {
                        objCmd.CommandText = InsertSql;
                        objCmd.ExecuteNonQuery();
                    }
                    catch (Exception exp)
                    {
                        string str = exp.Message;
                    }
                }
                try
                {
                    if (objConn.State == ConnectionState.Open)
                    {
                        objConn.Close();
                    }
                }
                catch (Exception exp)
                {
                    throw exp;
                }
                return true;
            }
    
            //#region 创建Excel并写入数据
            ///// <summary>
            ///// 导出Excel
            ///// </summary>
            ///// <param name="dt">数据源—DataTable</param>
            ///// <param name="title">表格标题</param>
            ///// <param name="fileSaveName">电子表格文件开头名(可空)</param>
            ///// <returns></returns>
            //public static string ExcelExport(DataTable dt, string fileSaveName)
            //{
            //    string docurl = "";
            //    Workbook wb = new Workbook();
            //    wb.Worksheets.Clear();
            //    wb.Worksheets.Add(fileSaveName);
            //    Worksheet ws = wb.Worksheets[0];
            //    Cells cells = ws.Cells;
    
            //    int rowIndex = 0; //记录行数游标
            //    int countCol = dt.Columns.Count; //获取返回数据表列数
    
            //    #region 样式设置
            //    //表头行样式
            //    Aspose.Cells.Style titleStyle = wb.Styles[wb.Styles.Add()];
            //    titleStyle.HorizontalAlignment = TextAlignmentType.Center;
            //    titleStyle.Font.Size = 15;
            //    titleStyle.Font.Name = "新宋体";
            //    titleStyle.Font.IsBold = true;
            //    titleStyle.ForegroundColor = System.Drawing.Color.FromArgb(216, 243, 205);
            //    titleStyle.Pattern = BackgroundType.Solid;
            //    //titleStyle.IsTextWrapped = true;
            //    titleStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
            //    titleStyle.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
            //    titleStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
            //    titleStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
    
            //    //表内容头样式
            //    Aspose.Cells.Style text_TitleStyle = wb.Styles[wb.Styles.Add()];
            //    text_TitleStyle.HorizontalAlignment = TextAlignmentType.Left;
            //    text_TitleStyle.Font.Size = 10;
            //    text_TitleStyle.Font.Name = "新宋体";
            //    text_TitleStyle.Font.IsBold = true;
            //    text_TitleStyle.ForegroundColor = System.Drawing.Color.White;
            //    text_TitleStyle.Pattern = BackgroundType.Solid;
            //    //text_TitleStyle.IsTextWrapped = true;
            //    text_TitleStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
            //    text_TitleStyle.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black;
            //    text_TitleStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
            //    text_TitleStyle.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
            //    text_TitleStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
            //    text_TitleStyle.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black;
            //    text_TitleStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
            //    text_TitleStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
    
            //    //表内容样式
            //    Aspose.Cells.Style textStyle = wb.Styles[wb.Styles.Add()];
            //    textStyle.HorizontalAlignment = TextAlignmentType.Left;
            //    textStyle.Font.Size = 10;
            //    textStyle.Font.Name = "新宋体";
            //    textStyle.Font.IsBold = false;
            //    textStyle.ForegroundColor = System.Drawing.Color.White;
            //    textStyle.Pattern = BackgroundType.Solid;
            //    //textStyle.IsTextWrapped = true;
            //    textStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
            //    textStyle.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black;
            //    textStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
            //    textStyle.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
            //    textStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
            //    textStyle.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black;
            //    textStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
            //    textStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
    
            //    //时间居中内容样式
            //    Aspose.Cells.Style timeStyle = wb.Styles[wb.Styles.Add()];
            //    timeStyle.HorizontalAlignment = TextAlignmentType.Left;
            //    timeStyle.Font.Size = 10;
            //    timeStyle.Font.Name = "新宋体";
            //    timeStyle.Font.IsBold = false;
            //    timeStyle.ForegroundColor = System.Drawing.Color.White;
            //    timeStyle.Pattern = BackgroundType.Solid;
            //    //timeStyle.IsTextWrapped = true;
            //    timeStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
            //    timeStyle.Borders[BorderType.LeftBorder].Color = System.Drawing.Color.Black;
            //    timeStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
            //    timeStyle.Borders[BorderType.RightBorder].Color = System.Drawing.Color.Black;
            //    timeStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
            //    timeStyle.Borders[BorderType.TopBorder].Color = System.Drawing.Color.Black;
            //    timeStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
            //    timeStyle.Borders[BorderType.BottomBorder].Color = System.Drawing.Color.Black;
            //    #endregion
    
            //    #region 电子表格表头
            //    ws.Cells[rowIndex, 0].PutValue("");
            //    ws.Cells[rowIndex, 0].SetStyle(titleStyle, true);
            //    for (int x = 1; x < countCol; x++)
            //    {
            //        ws.Cells[rowIndex, x].SetStyle(titleStyle, true);
            //    }
            //    cells.SetRowHeight(rowIndex, 26);
            //    cells.Merge(rowIndex, 0, 1, countCol);
            //    rowIndex++;
            //    #endregion
    
            //    #region 电子表格列属性信息
            //    for (int j = 0; j < countCol; j++)
            //    {
            //        string strName = dt.Columns[j].ColumnName;
            //        switch (strName)
            //        {
    
            //            case "LicenseFlag":
            //                strName = "是否上牌";
            //                break;
            //            case "NonLocalFlag":
            //                strName = "是否外地车";
            //                break;
            //            case "LicenseNo":
            //                strName = "车牌号";
            //                break;
            //            case "Vin":
            //                strName = "车型码(车架号)";
            //                break;
            //            case "EngineNo":
            //                strName = "发动机号";
            //                break;
            //            case "ModelCode":
            //                strName = "车辆品牌型号";
            //                break;
            //            case "EnrollDate":
            //                strName = "车辆初次登记日期";
            //                break;
            //            case "LoanFlag":
            //                strName = "是否贷款车";
            //                break;
            //            case "LoanBank":
            //                strName = "贷款银行";
            //                break;
            //            case "LoanContributing":
            //                strName = "贷款特约";
            //                break;
            //            case "TransferFlag":
            //                strName = "是否过户车";
            //                break;
            //            case "TransferFlagTime":
            //                strName = "过户时间";
            //                break;
            //            case "EnergyType":
            //                strName = "能源类型";
            //                break;
            //            case "LicenseTypeCode":
            //                strName = "车牌类型编码";
            //                break;
            //            case "CarTypeCode":
            //                strName = "行驶证车辆类型编码";
            //                break;
            //            case "VehicleType":
            //                strName = "车辆种类";
            //                break;
            //            case "VehicleTypeCode":
            //                strName = "车辆种类类型";
            //                break;
            //            case "VehicleTypeDetailCode":
            //                strName = "车辆种类类型详细";
            //                break;
            //            case "UseNature":
            //                strName = "车辆使用性质";
            //                break;
            //            case "UseNatureCode":
            //                strName = "使用性质细分";
            //                break;
            //            case "CountryNature":
            //                strName = "生成模式/产地";
            //                break;
            //            case "IsRenewal":
            //                strName = "是否续保";
            //                break;
            //            case "InsVehicleId":
            //                strName = "车型编码";
            //                break;
            //            case "Price":
            //                strName = "新车购置价格(含税)";
            //                break;
            //            case "PriceNoTax":
            //                strName = "新车购置价格(不含税)";
            //                break;
            //            case "Year":
            //                strName = "年款";
            //                break;
            //            case "Name":
            //                strName = "车型名称";
            //                break;
            //            case "Exhaust":
            //                strName = "排量";
            //                break;
            //            case "BrandName":
            //                strName = "品牌名称";
            //                break;
            //            case "LoadWeight":
            //                strName = "核定载质量/拉货的质量";
            //                break;
            //            case "KerbWeight":
            //                strName = "汽车整备质量/汽车自重";
            //                break;
            //            case "Seat":
            //                strName = "座位数";
            //                break;
            //            case "TaxType":
            //                strName = "车船税交税类型";
            //                break;
            //            case "VehicleIMG":
            //                strName = "车型图片";
            //                break;
            //            case "CustomerType":
            //                strName = "客户类型";
            //                break;
            //            case "IdType":
            //                strName = "证件类型";
            //                break;
            //            case "OwnerName":
            //                strName = "车主姓名";
            //                break;
            //            case "IdNo":
            //                strName = "证件号码";
            //                break;
            //            case "Address":
            //                strName = "地址";
            //                break;
            //            case "Mobile":
            //                strName = "联系电话";
            //                break;
            //            case "Email":
            //                strName = "联系邮箱";
            //                break;
            //            case "Sex":
            //                strName = "性别";
            //                break;
            //            case "Birthday":
            //                strName = "出生日期";
            //                break;
            //            case "Age":
            //                strName = "年龄";
            //                break;
            //            case "GeneralNumber":
            //                strName = "总机号码";
            //                break;
            //            case "LinkmanName":
            //                strName = "联系人姓名";
            //                break;
            //            case "CommercePolicyNo":
            //                strName = "上年度商业险保单号";
            //                break;
            //            case "CompulsoryPolicyNo":
            //                strName = "上年度交强险保单号";
            //                break;
            //            case "InsureCompanyCode":
            //                strName = "上年度承保公司编码";
            //                break;
            //            case "InsureCompanyName":
            //                strName = "上年度承保公司";
            //                break;
            //            case "CommercePolicyBeginDate":
            //                strName = "商业险开始时间";
            //                break;
            //            case "CommercePolicyEndDate":
            //                strName = "商业险结束时间";
            //                break;
            //            case "CompulsoryPolicyBeginDate":
            //                strName = "交强险开始时间";
            //                break;
            //            case "CompulsoryPolicyEndDate":
            //                strName = "交强险截至时间";
            //                break;
            //            case "CommerceTotalPremium":
            //                strName = "商业险总保费";
            //                break;
            //            case "CompulsoryTotalPremium":
            //                strName = "交强险总保费";
            //                break;
            //            case "TravelTax":
            //                strName = "车船税";
            //                break;
            //            case "SYInsuranceItem":
            //                strName = "商业险";
            //                break;
            //            case "JQInsurance":
            //                strName = "交强险";
            //                break;
            //            case "TravelInsurance":
            //                strName = "车船税";
            //                break;
            //            case "ToInsured":
            //                strName = "投保人信息";
            //                break;
            //            case "BeInsured":
            //                strName = "被保人信息";
            //                break;
            //        }
            //        ws.Cells[rowIndex, j].PutValue(strName);
            //        ws.Cells[rowIndex, j].SetStyle(text_TitleStyle, true);
            //    }
            //    cells.SetRowHeight(rowIndex, 24);
            //    rowIndex++;
            //    #endregion
    
            //    #region 处理导出数据
            //    for (int k = 0; k < dt.Rows.Count; k++)
            //    {
            //        for (int y = 0; y < countCol; y++)
            //        {
    
            //            if (dt.Columns[y].DataType == typeof(DateTime))
            //            {
            //                if (!String.IsNullOrEmpty(dt.Rows[k][y].ToString()))
            //                { ws.Cells[rowIndex, y].PutValue(DateTime.Parse(dt.Rows[k][y].ToString()).ToString("yyyy-MM-dd")); }
            //                else
            //                { ws.Cells[rowIndex, y].PutValue(" "); }
            //            }
            //            else
            //            {
            //                string str = dt.Rows[k][y].ToString();
    
            //                ws.Cells[rowIndex, y].PutValue(str);
            //            }
            //            try
            //            {
            //                ws.Cells[rowIndex, y].SetStyle(textStyle, true);
            //            }
            //            catch
            //            {
    
    
            //            }
            //        }
            //        cells.SetRowHeight(rowIndex, 24);
            //        rowIndex++;
            //    }
            //    #endregion
    
            //    #region 属性设置
            //    //属性设置
            //    ws.UnFreezePanes();
            //    ws.FreezePanes(2, 1, 2, 0);
            //    ws.AutoFitColumns();
            //    ws.AutoFilter.SetRange(1, 0, countCol - 1);
            //    #endregion
    
            //    #region 存储文件名
            //    //存储文件名
            //    fileSaveName += ".xls";
            //    //存储文件地址
            //    docurl = "C:\" + fileSaveName;// HttpContext.Current.Server.MapPath().ToString();
            //    wb.Save(docurl);
            //    #endregion
    
            //    return docurl;
    
            //}
            //#endregion
            #endregion
    
            /// <summary>获取Excel文件数据表列表
            /// </summary>
            public static ArrayList GetExcelTables(string ExcelFileName)
            {
                string connStr = "";
                string fileType = System.IO.Path.GetExtension(ExcelFileName);
                if (string.IsNullOrEmpty(fileType)) return null;
    
                if (fileType == ".xls")
                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFileName + ";Extended Properties="Excel 8.0;HDR=YES;IMEX=1"";
                else
                    connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFileName + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";
                DataTable dt = new DataTable();
                ArrayList TablesList = new ArrayList();
                if (File.Exists(ExcelFileName))
                {
                    using (OleDbConnection conn = new OleDbConnection(connStr))
                    {
                        try
                        {
                            conn.Open();
                            dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                        }
                        catch (Exception exp)
                        {
                            throw exp;
                        }
    
                        //获取数据表个数
                        int tablecount = dt.Rows.Count;
                        for (int i = 0; i < tablecount; i++)
                        {
                            string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');
                            if (TablesList.IndexOf(tablename) < 0)
                            {
                                TablesList.Add(tablename);
                            }
                        }
                    }
                }
                return TablesList;
            }
    
            /// <summary>将Excel文件导出至DataTable(第一行作为表头,默认为第一个数据表名)
            /// </summary>
            /// <param name="ExcelFilePath">Excel文件路径</param>
            public static DataTable InputFromExcel(string ExcelFilePath)
            {
                if (!File.Exists(ExcelFilePath))
                {
                    throw new Exception("Excel文件不存在!");
                }
                string fileType = System.IO.Path.GetExtension(ExcelFilePath);
                if (string.IsNullOrEmpty(fileType)) return null;
    
                string connStr = string.Empty;
                string TableName = string.Empty;
                if (fileType == ".xls")
                {
                    connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties="Excel 8.0;HDR=YES;IMEX=1"";
                }
                else
                {
                    connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";
                }
    
                //如果数据表名不存在,则数据表名为Excel文件的第一个数据表
                ArrayList TableList = new ArrayList();
                TableList = GetExcelTables(ExcelFilePath);
    
                TableName = TableList[0].ToString().Trim();
    
                DataTable table = new DataTable();
                OleDbConnection dbcon = new OleDbConnection(connStr);
                if (!TableName.Contains("$"))
                {
                    TableName = TableName + "$";
                }
                OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "]", dbcon);
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
    
                try
                {
                    if (dbcon.State == ConnectionState.Closed)
                    {
                        dbcon.Open();
                    }
                    adapter.Fill(table);
                }
                catch (Exception exp)
                {
                    throw exp;
                }
                finally
                {
                    if (dbcon.State == ConnectionState.Open)
                    {
                        dbcon.Close();
                    }
                }
                return table;
            }
    
            /// <summary>将Excel文件导出至DataTable(指定表头)
            /// </summary>
            /// <param name="ExcelFilePath"></param>
            /// <param name="TableName"></param>
            /// <param name="Column"></param>
            /// <returns></returns>
            public static DataTable InputFromExcel(string ExcelFilePath, string TableName, string Column)
            {
                string connStr = "";
                if (!File.Exists(ExcelFilePath))
                {
                    throw new Exception("Excel文件不存在!");
                }
                string fileType = System.IO.Path.GetExtension(ExcelFilePath);
                if (string.IsNullOrEmpty(fileType)) return null;
    
                if (fileType == ".xls")
                {
                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties="Excel 8.0;HDR=YES;IMEX=1"";
                }
                else
                {
                    connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";
                }
                if (string.IsNullOrEmpty(Column))
                {
                    Column = "*";
                }
                //如果数据表名不存在,则数据表名为Excel文件的第一个数据表
                ArrayList TableList = new ArrayList();
                TableList = GetExcelTables(ExcelFilePath);
    
                if (TableList.IndexOf(TableName) < 0)
                {
                    TableName = TableList[0].ToString().Trim();
                }
    
                DataTable table = new DataTable();
                OleDbConnection dbcon = new OleDbConnection(connStr);
                OleDbCommand cmd = new OleDbCommand(string.Format("select {0} from [{1}$]", Column, TableName), dbcon);
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
    
                try
                {
                    if (dbcon.State == ConnectionState.Closed)
                    {
                        dbcon.Open();
                    }
                    adapter.Fill(table);
                }
                catch (Exception exp)
                {
                    throw exp;
                }
                finally
                {
                    if (dbcon.State == ConnectionState.Open)
                    {
                        dbcon.Close();
                    }
                }
                return table;
            }
    
            /// <summary>获取Excel文件指定数据表的数据列表
            /// </summary>
            /// <param name="ExcelFileName">Excel文件名</param>
            /// <param name="TableName">数据表名</param>
            public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName)
            {
                DataTable dt = new DataTable();
                ArrayList ColsList = new ArrayList();
                if (File.Exists(ExcelFileName))
                {
                    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))
                    {
                        conn.Open();
                        dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null });
    
                        //获取列个数
                        int colcount = dt.Rows.Count;
                        for (int i = 0; i < colcount; i++)
                        {
                            string colname = dt.Rows[i]["Column_Name"].ToString().Trim();
                            ColsList.Add(colname);
                        }
                    }
                }
                return ColsList;
            }
        }
    

      

  • 相关阅读:
    10 种保护 Spring Boot 应用的绝佳方法
    Redis 如何分析慢查询操作?
    Spring Boot 主类及目录结构介绍
    Redis 再牛逼,也得设置密码!!
    Spring Data Redis 详解及实战一文搞定
    Spring Boot Redis Cluster 实战干货
    超详细的 Redis Cluster 官方集群搭建指南
    Redis Linux 安装运行实战全记录
    hdu 4790 Just Random (思路+分类计算+数学)
    poj 1328 Radar Installation(贪心)
  • 原文地址:https://www.cnblogs.com/XuPengLB/p/7826725.html
Copyright © 2020-2023  润新知