Net 读取Excel

别人的参考代码

//引用Microsoft.Office.Interop.Excel.dll文件
//添加using
using Microsoft.Office.Interop.Excel;
using Excel=Microsoft.Office.Interop.Excel;//设置程序运行语言
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//创建Application
Excel.Application xlApp = new Excel.Application();
//设置是否显示警告窗体
excelApp.DisplayAlerts = false;
//设置是否显示Excel
excelApp.Visible = false;
//禁止刷新屏幕
excelApp.ScreenUpdating = false;
//根据路径path打开
Excel.Workbook xlsWorkBook = excelApp.Workbooks.Open(path, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//获取Worksheet对象
Excel.Worksheet xlsWorkSheet = (Worksheet)xlsWorkBook.Worksheets["sales plan"];***获取最后一行、一列的两种方法***
//获取已用的范围数据
int rowsCount = xlsWorkSheet.UsedRange.Rows.Count;
int colsCount = xlsWorkSheet.UsedRange.Columns.Count;
int rowsCount = xlsWorkSheet.get_Range("A65536", "A65536").get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
int colsCount = xlsWorkSheet.get_Range("ZZ1", "ZZ1").get_End(Microsoft.Office.Interop.Excel.XlDirection.xlToLeft).Column;***将Excel数据存入二维数组***
//rowsCount:最大行  colsCount:最大列
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Cells[rowsCount, colsCount];
Range rng = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.get_Range(c1, c2);
object[,] exceldata = (object[,])rng.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);//在第一列的左边插入一列
Excel.Range xlsColumns = (Excel.Range)xlsWorkSheet.Columns[1, System.Type.Missing];
xlsColumns.Insert(XlInsertShiftDirection.xlShiftToRight, Type.Missing);
//xlsSheetTemplateMajor_Meisai.Cells.get_Range(xlsSheetTemplateMajor_Meisai.Cells[1, 1], xlsSheetTemplateMajor_Meisai.Cells[65535, 1]).Insert(Type.Missing, Type.Missing);Excel.Range rng;rng = worksheet.get_Range("A:A", "A:A");rng.Insert(Excel.XlDirection.xlToRight, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
Excel.Range rng = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Columns[12, Type.Missing];
rng.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);//删除行
Range deleteRng = (Range)xlsWorkSheetSapExcel.Rows[2, System.Type.Missing];
deleteRng.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);//删除一列数据
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 11]).Select();
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 11]).EntireColumn.Delete(0);
((Excel.Range)xlsSheetShareMajor_Meisai.Cells[1, 3]).EntireColumn.Delete (0);//设置背景色为红色
xlsWorkSheet.get_Range("A1", "A1").Interior.ColorIndex = 3;//设置Format属性  属性值可以通过在vba中录宏得到
Microsoft.Office.Interop.Excel.Range range1 = xlsWorkSheetAdd.get_Range("J1", "J65535");
range1.NumberFormat = "@";//文本格式
range1 = xlsWorkSheetAdd.get_Range("L1", "L65535");
range1.NumberFormat = "0.00";//保留两位小数
Excel.Range rng = xlsSheetShareMajor_Meisai.Columns["I", System.Type.Missing] as Excel.Range;
rng.NumberFormatLocal =@"yyyy/m/d";//设置日期格式//替换
Range Drng = xlsWorkSheetTemplate.get_Range("D1", "D65535");
Drng.Replace(" ", "", XlLookAt.xlPart, XlSearchOrder.xlByColumns, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
Drng.TextToColumns(Drng, Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierSingleQuote, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);//分列处理 设置为文本
Range TextToColumnRng = xlsWorkSheet.get_Range("E1", "E65535");
xlsWorkSheet.get_Range("E1", "E65535").TextToColumns(TextToColumnRng, Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierSingleQuote, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);//设置公式
rng = xlMergeFileWorkSheet.get_Range("D2", "D" + rowcount);//设置列范围
rng.Formula = @"=IF(RC[-3]=""H"",""Survivor"",""Donor"")";//设置公式  @的问题
//rng.NumberFormat = "$0.00";//设置格式
copyRng = xlsSheetTemplateMajor_Meisai.get_Range("N3", "N" + lastRowTemplate);
copyRng.Formula = "=VLOOKUP(RC[-12],AR残!C[-13]:C[-11],2,0)";//通过行、列的索引获取值
string f = Convert.ToString(xlsSheetShareMajor_Meisai.get_Range(xlsSheetShareMajor_Meisai.Cells[2, 1], xlsSheetShareMajor_Meisai.Cells[2,1]).Value2);//筛选
//确定筛选范围
D1_rng = D1_TemSheet.Cells.get_Range(D1_TemSheet.Cells[1, 1], D1_TemSheet.Cells[1, 50]);
//执行筛选动作
rng.AutoFilter(5, "S", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
rng.AutoFilter(6, "H", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, "F", true);
D1_rng.AutoFilter(D1_Column + 2, "#N/A", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues,"#N/A",false);//复制粘贴
D2_rng.Copy(Type.Missing);
D2_TemSheet.Cells.get_Range(D2_TemSheet.Cells[2, (D2_Column + 1)], D2_TemSheet.Cells[2, (D2_Column + 1)]).PasteSpecial(Excel.XlPasteType.xlPasteValues, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);//Find查找
rng = mySheet.get_Range("A1", "IV10").Find(arrLabel[j], Type.Missing,Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);//文字占满单元格
range.EntireColumn.AutoFit();//另存
xlsWorkBook.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);***关闭对象***
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWorkSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWorkBook);
excelApp.Quit();
Kill(excelApp);//调用方法关闭进程
GC.Collect();/// <summary>
/// 关闭Excel进程
/// </summary>
public class KeyMyExcelProcess
{[DllImport("User32.dll", CharSet = CharSet.Auto)]public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);public static void Kill(Microsoft.Office.Interop.Excel.Application excel){try{IntPtr t = new IntPtr(excel.Hwnd);  //得到这个句柄,具体作用是得到这块内存入口int k = 0;GetWindowThreadProcessId(t, out k);  //得到本进程唯一标志kSystem.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);  //得到对进程k的引用p.Kill();   //关闭进程k}catch (System.Exception ex){throw ex;}}
}//关闭打开的Excel方法public void CloseExcel(Microsoft.Office.Interop.Excel.Application ExcelApplication, Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook)
{ExcelWorkbook.Close(false, Type.Missing, Type.Missing);ExcelWorkbook = null;ExcelApplication.Quit();GC.Collect();KeyMyExcelProcess.Kill(ExcelApplication);
}

自己的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;/// <summary>
/// 参考文档
/// https://www.jb51.net/article/132309.htm
/// </summary>namespace ExcelParser
{// excelusing Microsoft.Office.Interop.Excel;using System.Diagnostics;using MsExcel = Microsoft.Office.Interop.Excel;public class ExcelTool{public MsExcel.Application NewApp(bool visiable=false, bool alert=false){MsExcel.Application xlApp = new MsExcel.Application();//设置是否显示警告窗体xlApp.DisplayAlerts = alert;//设置是否显示ExcelxlApp.Visible = visiable;//禁止刷新屏幕, 可以加速显示//xlApp.ScreenUpdating = false;return xlApp;}public MsExcel.Workbook OpenFile(ref MsExcel.Application app,string path){return app.Workbooks.Open(path);}public void ExitApp(ref MsExcel.Application app){// workbook 索引从1开始for(int i = app.Workbooks.Count; i>0; i--) { app.Workbooks.Item[i].Close(false); // don't save changes}app.Workbooks.Close();app.Quit();}public void ForceKill(string processName="excel"){Process[] procs = Process.GetProcessesByName(processName);foreach (var pro in procs){pro.Kill();//没有更好的方法,只有杀掉进程}}public void SaveAsXlsx(ref MsExcel.Workbook wb, string path){var fmtPath = Path.GetFullPath(path);wb.SaveAs2(fmtPath, MsExcel.XlFileFormat.xlOpenXMLWorkbook);}public void SaveAsXlsm(ref MsExcel.Workbook wb, string path){var fmtPath = Path.GetFullPath(path);wb.SaveAs2(fmtPath, MsExcel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled);}public void RunExcelMacro(ref MsExcel.Application app, string macroName, object[] parameters, out object rtnValue){// 根据参数组是否为空,准备参数组对象object[] paraObjects;if (parameters == null)paraObjects = new object[] { macroName };else{int paraLength = parameters.Length;paraObjects = new object[paraLength + 1];paraObjects[0] = macroName;for (int i = 0; i < paraLength; i++)paraObjects[i + 1] = parameters[i];}rtnValue = this.RunMacro(app, paraObjects);}private object RunMacro(object app, object[] oRunArgs){object objRtn;     // 声明一个返回对象// 反射方式执行宏objRtn = app.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, app, oRunArgs);return objRtn;}public void PrintDebug(ref MsExcel.Workbook wb){Debug.WriteLine($"File format: {wb.FileFormat}, title: {wb.FullName}, VBA: {wb.HasVBProject}, app version: {wb.Application.Version} ");Debug.WriteLine($"Book Title:{wb.FullName}, saved?:{wb.Saved}, wbs:{wb.Worksheets.Count}");for(int i=0; i<wb.Worksheets.Count; i++){Worksheet sheet = wb.Worksheets.Item[i+1];var rg = sheet.UsedRange;Debug.WriteLine($"Sheet {i+1} => title:{sheet.Name}, range:{rg.Row},{rg.Column},{rg.Rows.Count}x{rg.Columns.Count}");}}public void ReadTest(ref MsExcel.Workbook wb){for (int i = 1; i <= wb.Worksheets.Count; i++){Worksheet sheet = wb.Worksheets.Item[i];Debug.WriteLine($"Sheet {sheet.Name} values:");var rg = sheet.UsedRange;for (int j = 1; j <= rg.Rows.Count; j++){Debug.Write($"{rg.Row+j-1} => ");for (int k = 1; k <= rg.Columns.Count; k++){Range cell = rg.Cells.Item[j, k];dynamic val = 0;string ty = "";if (cell.Value2 == null){// cell is blankval = null;ty = "null";}else if (cell.Value2 is string){// cell is textval = (string)cell.Value2;ty = "text";}else if (cell.Value is double){// cell is number;val = (double)cell.Value;ty = "number";}else if (cell.Value2 is double){// cell is dateval = DateTime.Now;ty = "date";}Debug.Write($"[{k-1+rg.Column}]={val}/{ty}, ");}Debug.WriteLine("");}}}}
}

使用代码:

        private void btn_read_xlsm_Click(object sender, EventArgs e){var app = msTool.NewApp();var wb = msTool.OpenFile(ref app, xlsmPath);msTool.PrintDebug(ref wb);msTool.ReadTest(ref wb);msTool.ExitApp(ref app);}private void button1_Click(object sender, EventArgs e){msTool.ForceKill();}private void button2_Click(object sender, EventArgs e){var app = msTool.NewApp(true);var wb = msTool.OpenFile(ref app, xlsmPath);msTool.PrintDebug(ref wb);object retval = null;msTool.RunExcelMacro(ref app, "Button2_Click", null, out retval);msTool.ReadTest(ref wb);msTool.ExitApp(ref app);}

Demo Excel:

C# excel net core读取xlsm相关推荐

  1. NET CORE读取Excel.xlsx单元格内的图片,并关联当前业务ID推送图片到指定服务器...

    NET CORE读取Excel.xlsx单元格图片的场景,一般是批量导入业务数据,例如:药品的图片,医师资格证,商品上架.商家营业资质.水果信息.用户头像等等 这里我截个图,图文并茂更好理解 特别声明 ...

  2. Excel VBA简单需求实践,包含对Excel基本的读取,校验,复写操作

    该文为想要学习VBA编程的会计和编程同学有使用VBA实现Excel自动化处理和一定的个性化定制Excel操作提供参考 第一篇为::VBA简单语法 第二篇为: Excel 编写第一个简单的VBA程序 第 ...

  3. android读取excel数据库,Android 读取Excel数据并保存在本地数据库

    在工作中遇到需要将Excel的数据读取出来并保存在本地数据库中的操作,数据如下: 图片.png 需要做以下准备: 读取Excel的jar包[文章末尾会分享该jar包] 保存数据的数据库框架,在这里我们 ...

  4. python处理excel文件-python读取excel文件

    # 最近写项目需要,通过读取excel文件导入数据至数据库 第一种方式:xlrd方式 安装模块: pip install xlrd 导入模块: import xlrd 拿到操作excel句柄,读取ex ...

  5. python读取excel表格-python读取excel表格中的数据

    使用python语言实现Excel 表格中的数据读取,需要用到xlrd.py模块,实现程序如下: import xlrd #导入xlrd模块 class ExcelData(): def __init ...

  6. Django框架(上传Excel文件并读取)

    博主今天整理下Django框架中上传Excel文件并读取 博主是要在管理平台中新增用例的维护功能,想着通过上传Excel文件来展示用例,下面是项目的路径图: 首先先建数据库模型 model.py 可以 ...

  7. java读取excel数据_Java读取Excel内容(转)

    借助于apathe的poi.jar,由于上传文件不支持.jar所以请下载后将文件改为.jar,在应用程序中添加poi.jar包,并将需要读取的excel文件放入根目录即可 本例使用java来读取exc ...

  8. python3字典写入excel_python3:excel操作之读取数据并返回字典 + 写入的案例

    excel写入数据,使用openpyxl库 class WriteExcel: def __init__(self,path): self.path = path def write_excel(se ...

  9. matlab 读取excel一列,读取excel中的数据把第一列相同的所有行数据输出成一个excel...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 284 1113436773300.00 1113436773.30 44.55 284 1113436773400.00 1113436773.40 4 ...

  10. 部署Chart应用并使用.net core读取Kubernetes中的configMap

    上一篇文章讲了 k8s使用helm打包chart并上传到腾讯云TencentHub,今天就讲一下使用Helm部署应用并使用configMap代替asp.net core 中的appsettings.j ...

最新文章

  1. CentOS 7下用firewall-cmd
  2. 在不同浏览器中,input里面的输入光标大小表现形式却大不相同
  3. 《Microsoft Sql server 2008 Internals》读书笔记--第五章Table(4)
  4. Android框架式编程之MVP架构
  5. 形态学图像处理(二)
  6. 深入浅出 Spring 架构设计
  7. 我是这样理解HTTP和HTTPS区别的
  8. Swift NSDate的一个分类,把Mon Apr 04 19:45:37 +0800 2016这种格式的时间转换为2016-04-04 11:45:37 +0000
  9. 把C#当作脚本语言来用
  10. SaaSpace:12种最好的免费甘特图软件工具
  11. 浅谈木材加工企业的电气火灾隐患及电气火灾监控系统的应用
  12. CVPR 2020 | 旷视研究院提出优化领域自适应物体检测性能的类别正则化框架
  13. 【C#】打印机ZPL指令打印图片,将图片转成十六进制指令
  14. Spring-Cloud之Spring Cloud Netflix Eureka服务注册与发现
  15. 我第一个用DirextX做的2D游戏——炮炮兵考眼力
  16. 沉浸其中,二次元高清图片
  17. VUE2版本引入Element UI
  18. PWN入门(3)覆盖堆栈上的变量
  19. 信号完整性学习笔记-IBIS模型
  20. Python 命令行参数详解

热门文章

  1. Vue学习---插槽篇
  2. package.json文件指南
  3. 《新说文解字》太极初成:道生一,一生二,二生三,三生万物
  4. JS实现环绕地球飞行的3D飞行线动画效果(JS+HTML)
  5. BZOJ[2827]千山鸟飞绝 线段树
  6. word打开文档很久很慢_win7系统打开word文档很慢需要等待很长时间的五种解决方法...
  7. 一个程序员的心路历程
  8. SubmitButton
  9. 高登学苑-解密携程4.9分的秘诀学习笔记
  10. 简单提取iOS13的ipsw固件的内置壁纸(或文件)