Excel导出

1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Data;
using Aspose.Cells;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.Script.Serialization;

namespace PublicBase.Common
{
    public class CommonFunction
    {
        /// 
        /// excel导出
        /// 
        /// 需要导出的对象集合
        /// 导出文件名
        /// 
        public static Stream ExportToExcel(List list, string filename, Func func)
        where T : class,new()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                System.IO.StringWriter tw = new System.IO.StringWriter();
                sb.Append("");
                sb.Append("");
                sb.Append("");
                sb.Append("");
                sb.Append("");
                sb.Append(" ");
                sb.Append("");
                sb.Append("");
                sb.Append("
"); int i = 0; sb.Append(""); //导入表头 string rowspan = "1"; string colspan = "1"; sb.Append(""); int columnsCount = 0; var infos = typeof(T).GetProperties(); infos = infos.Where(item => Attribute.IsDefined(item, typeof(DisplayNameAttribute))).Where(func).ToArray(); columnsCount = infos.Length; sb.Append(""); sb.Append(""); sb.Append(""); for (i = 0; i < infos.Length; i++) { string fieldName = ((DisplayNameAttribute)Attribute.GetCustomAttribute(infos[i], typeof(DisplayNameAttribute))).DisplayName; sb.Append(""); } sb.Append(""); //导入数据 int j = 0; for (i = 0; i < list.Count; i++) { sb.Append(""); for (j = 0; j < infos.Length; j++) { string fieldValue = ""; if (infos[j].GetValue(list[i], null) != null) { fieldValue = infos[j].GetValue(list[i], null).ToString(); } sb.Append(""); } sb.Append(""); } sb.Append("
"); sb.Append(filename); sb.Append("
"); sb.Append(fieldName); sb.Append("
"); sb.Append(fieldValue); sb.Append("
"); sb.Append("
"); sb.Append(""); System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())); return ms; } catch (Exception ex) { throw ex; } } public static void ThrowAppException(string msg) { throw new Exception(msg); } public static void ThrowAppException(Exception exp) { throw new Exception(exp.Message); } public static DataTable ExcelToDataTable(Stream stream) { try { DataTable tb = new DataTable(); Workbook wb = new Workbook(); wb.Open(stream); var wsCells = wb.Worksheets[0].Cells; tb = wsCells.ExportDataTable(0, wsCells.MinColumn, wsCells.MaxDataRow + 1, wsCells.MaxColumn + 1); tb.Rows.RemoveAt(0); return tb; } catch { throw new Exception("您使用的模板格式不正确,请下载使用正确的模板!"); } } /// /// 根据Json返回DateTable,JSON数据格式如: /// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]} /// /// Json字符串 /// public static DataTable JsonToDataTable(string strJson) { //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //获取数据 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split(','); //创建表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split(':'); dc.ColumnName = strCell[0]; tb.Columns.Add(dc); } tb.AcceptChanges(); } //增加内容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } /// /// Json格式转换成键值对,键值对中的Key需要区分大小写 /// /// 需要转换的Json文本数据 /// public static Dictionary JsonToDictionary(string JsonData) { object Data = null; Dictionary Dic = new Dictionary(); if (JsonData.StartsWith("[")) { //如果目标直接就为数组类型,则将会直接输出一个Key为List的List>集合 //使用示例List> ListDic = (List>)Dic["List"]; List> List = new List>(); MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 foreach (Match ListItem in ListMatch) { List.Add(JsonToDictionary(ListItem.ToString()));//递归调用 } Data = List; Dic.Add("List", Data); } else { MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值 foreach (Match item in Match) { try { if (item.Groups[2].ToString().StartsWith("[")) { //如果目标是数组,将会输出一个Key为当前Json的List>集合 //使用示例List> ListDic = (List>)Dic["Json中的Key"]; List> List = new List>(); MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 foreach (Match ListItem in ListMatch) { List.Add(JsonToDictionary(ListItem.ToString()));//递归调用 } Data = List; } else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入 Dic.Add(item.Groups[1].ToString(), Data); } catch { } } } return Dic; } /// /// 对象转JSON /// /// 对象 /// JSON格式的字符串 public static string ObjectToJson(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); } } } }

从Execl导入数据到DataTable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;
using System.Data.OleDb;

namespace PublicBase.Common
{
    public class ImportFromExcel
    {
        public static DataTable InputFromExcel(string ExcelFilePath, string TableName)
        {
            if (!File.Exists(ExcelFilePath))
            {
                throw new Exception("Excel文件不存在!");
            }
            ArrayList TableList = new ArrayList();
            TableList = GetExcelTables(ExcelFilePath);
            if (TableName.IndexOf(TableName) < 0)
            {
                TableName = TableList[0].ToString().Trim();
            }
            DataTable table = new DataTable();
            OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0");
            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;
        }
        public static ArrayList GetExcelTables(string ExcelFileName)
        {
            DataTable dt = new DataTable();
            ArrayList TablesList = 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))
                {
                    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;
        }
    }
}


你可能感兴趣的:(ASP.NET)