网页导出EXCEL,调用该方法 前台会下载EXCEL

/// <summary>/// Excle导出数据/// </summary>/// <typeparam name="T">类对象<\typeparam>/// <param name="list">对象数据</param>/// <param name="column">类字段,字段对应列名</param>/// <param name="filename">excel表名</param>public void OutExcel<T>(List<T> list, Dictionary<string, string> column, string filename){if (list == null || list.Count == 0 || column == null || column.Count == 0){return;}StringWriter sw = new StringWriter();//-------------------------------表头读取开始------------------------------------------------string title = string.Empty;foreach (KeyValuePair<string, string> kvp in column){title += kvp.Value + "\t";}title = title.Substring(0, title.LastIndexOf("\t"));sw.WriteLine(title);//-------------------------------表头读取结束--------------------------------------------------------//--------------------------------数据读取start----------------------------------------------------------------------------------Type objType = typeof(T);BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识 PropertyInfo[] propInfoArr = objType.GetProperties(bf); //获取映射列表foreach (T model in list){System.Text.StringBuilder data = new System.Text.StringBuilder();foreach (string key in column.Keys){foreach (PropertyInfo propInfo in propInfoArr){if (key == propInfo.Name)//判断头相对应的字段 {PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);if (modelProperty != null){object objResult = modelProperty.GetValue(model, null);//获取值                        data.Append(((objResult == null) ? string.Empty : objResult) + "\t");}}}}var temp = data.ToString();temp = temp.Substring(0, temp.LastIndexOf("\t"));sw.WriteLine(temp);}//------------------------------------------end----------------------------------------------------------------------------------sw.Close();//读取数据结束//-----------------------------------输出excel-------------------------------------------------------------HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".xls");HttpContext.Current.Response.ContentType = "application/ms-excel";HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");HttpContext.Current.Response.Write(sw.ToString());HttpContext.Current.Response.End();//-------------------------------------------------------------------------------------------------------------               }

调用例子

  List<easy_CX> es = a.ToObjectFromJson<List<easy_CX>>();Dictionary<string, string> mydict = new Dictionary<string, string>();OutExcel(es,mydict,"all_down");

DataGridview中的数据导出EXCEL

 public bool ExportDataGridview(DataGridView gridView, bool isShowExcle){if (gridView.Rows.Count == 0){return false;}//创建Excel对象Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();excel.Application.Workbooks.Add(true);//生成字段名称for (int i = 0; i < gridView.ColumnCount; i++){excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;}//填充数据for (int i = 0; i < gridView.RowCount - 1; i++)   //循环行{for (int j = 0; j < gridView.ColumnCount; j++) //循环列{if (gridView[j, i].ValueType == typeof(string)){excel.Cells[i + 2, j + 1] = "'" + gridView.Rows[i].Cells[j].Value.ToString();}else{excel.Cells[i + 2, j + 1] = gridView.Rows[i].Cells[j].Value.ToString();}}} excel.Visible = false;excel.DisplayAlerts = false;excel.AlertBeforeOverwriting = false;excel.Save("c:\\321.xls");excel.Quit();return true;}

把DataTable导出为EXCEL

        public void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName){if (tmpDataTable == null)return;int rowNum = tmpDataTable.Rows.Count;int columnNum = tmpDataTable.Columns.Count;int rowIndex = 1;int columnIndex = 0;Excel.Application xlApp = new Excel.Application();xlApp.DefaultFilePath = "";xlApp.DisplayAlerts = true;xlApp.SheetsInNewWorkbook = 1;Excel.Workbook xlBook = xlApp.Workbooks.Add(true);//将DataTable的列名导入Excel表第一行foreach (DataColumn dc in tmpDataTable.Columns){columnIndex++;xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;}//将DataTable中的数据导入Excel中for (int i = 0; i < rowNum; i++){rowIndex++;columnIndex = 0;for (int j = 0; j < columnNum; j++){columnIndex++;xlApp.Cells[rowIndex, columnIndex] = "'" + tmpDataTable.Rows[i][j].ToString();}}//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));xlBook.SaveCopyAs(strFileName);xlBook.Close(false);}

将EXCEL转换为DataTable  之后存入数据库常用于批量导入

 // <summary>/// 将Excel文件导出至DataTable(第一行作为表头)/// </summary>/// <param name="ExcelFilePath">Excel文件路径</param>/// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param>public static DataTable InputFromExcel(string ExcelFilePath, string TableName){if (!File.Exists(ExcelFilePath)){throw new Exception("Excel文件不存在!");}//如果数据表名不存在,则数据表名为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.ACE.OLEDB.12.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.ACE.OLEDB.12.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;}

C#EXCEL操作大全相关推荐

  1. Delphi Excel 操作大全【CreateOleObject( 'Excel.Application' )】

    (一) 使用动态创建的方法 首先创建 Excel 对象,使用ComObj: var ExcelApp: Variant; ExcelApp := CreateOleObject( 'Excel.App ...

  2. pandas神器操作excel表格大全(数据分析数据预处理)

    使用pandas库操作excel,csv表格操作大全 [点我下载本文PDF电子版] 关注公众号"轻松学编程"了解更多,文末有公众号二维码,可以扫码关注哦. 前言 准备三份csv表格 ...

  3. excel操作练习_你见过最好的Excel教程有哪些?

    教程领到手,学习不用愁!领 答案找一套知识兔Excel教程,学习Excel基本功能,学习Excel高频应用技能--之后很简单,就是反复的练,刻意的练习,不然就多应用.兴趣使然,以应用为导向,学以致用, ...

  4. Excel函数大全-10查找和引用函数

    10查找和引用函数 10x01 ADDRESS 函数 语法 10x02 AREAS 函数 语法 10x03 CHOOSE 函数 语法 10x04 COLUMN 函数 语法 10x05 COLUMNS ...

  5. 计算机表格函数知识点,Excel知识点大全

    <Excel知识点大全>由会员分享,可在线阅读,更多相关<Excel知识点大全(29页珍藏版)>请在人人文库网上搜索. 1.实用标准文档必修:excel上机考试知识点一.数据的 ...

  6. pandas操作大全

    pandas操作大全 一.pandas操作大全 1.1 导入数据 1.2 导出数据 1.3 添加日期索引 1.4 查看.检查数据 1.5 数据选取 1.6 数据清理 1.7 筛选,排序和分组依据 1. ...

  7. Excel快捷键大全(2023最新版总结)

    案例:Excel快捷键大全 [作为一名打工人,我总是要用到Excel表格,大家平常在使用Excel时都有什么比较好用的快捷键推荐吗?] Excel是一款功能强大的电子表格软件,可以用于数据管理.计算. ...

  8. Excel函数大全-11数学和三角函数

    11数学和三角函数 全部数学和三角函数列表 11x01 AGGREGATE 函数 语法 11x02 ARABIC 函数 语法 11x03 BASE 函数 语法 11x04 CEILING 函数 语法 ...

  9. Excel函数大全-13文本函数

    13文本函数 13x01 ASC 函数 语法 13x02 BAHTTEXT 函数 语法 13x03 CHAR 函数 语法 13x04 CLEAN 函数 语法 13x05 CODE 函数 语法 13x0 ...

最新文章

  1. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 按钮:按钮组
  2. 在线学习与离线学习如何区分
  3. ajaxbootstrap
  4. Supervised Descent Method and its Applications to Face Alignment
  5. 龙果学院mysql分布式集群代码_龙果学院-MySQL大型分布式集群解决方案
  6. 最常见的水平拆分规则
  7. 美团靠外卖和到店业务赚来的钱
  8. 【C++模块实现】| 【07】对于互斥、自旋锁、条件变量、信号量简介及封装
  9. VB2010网络通信服务器
  10. 软件工程——毕业论文管理系统
  11. 2022年陕西中级审计师考试练习题及答案
  12. [OpenCV实战]1 基于深度学习识别人脸性别和年龄
  13. 神奇的BUG——MATLAB之1
  14. EasyRecovery14个人版电脑数据恢复软件支持Win/Mac
  15. apollo学习之---(17)commen-math学习
  16. 澳洲留学生论文写作必备好用软件or网站
  17. linux p4 命令行,linux下使用P4(命令行)
  18. 常用链接ssh服务器的工具(推荐)
  19. 【渝粤题库】陕西师范大学201771 中国古代文学(一) 作业
  20. 前端基础_JavaScript

热门文章

  1. QQ空间视频下载详细教程(手机端)
  2. abp vnext没有生成动态代理js代码
  3. 13年android手机top,2013年1月安卓热门机型Top20
  4. 2015异常问题解决方案经验总结(一)
  5. 光线投射与光线跟踪算法归纳
  6. python浓缩(13)面向对象编程
  7. 算法介绍及实现——马尔可夫链、隐马尔可夫链(附Python实现)
  8. 数字化转型 — 新能源汽车 — 产品设计与研发流程
  9. 2022广东省安全员C证第三批(专职安全生产管理人员)考试题库及模拟考试
  10. Hone Hone Clock 以及小松鼠等代码以及插入方法