C# 代码 - Excel相关

该代码片段展示了如何使用C#访问Excel工作表,通过SpecialCells方法获取非空白内容的最后一行行号,特别注意背景色填充不会被计作有效行数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

>>创建保存:
using System;
using Excel = Microsoft.Office.Interop.Excel;

// 启动Excel应用程序

var app =  new Excel.Application();
app.Visible =  true;

// 添加一个新的工作簿

var book = app.Workbooks.Add();
//var book = excelApp.Workbooks.Open(filePath, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, true);

var sheet = (Excel.Worksheet)book.Sheets[1];
//var sheet = (Excel.Worksheet)book.Sheets["Sheet1"];

//read
string test= (string)sheet.Cells[i, 1].Value;  //如单元格为数字内容会报错
string test2= sheet.Cells[i, 1].Value.ToString();//如单元格为数字内容会转为string

//write
((Excel.Range)sheet.Cells[1,1]).Font.FontStyle ="Bold";
((Excel.Range)sheet.Cells[1,1]).Value = "xxx";




// 保存工作簿
book.SaveAs("D:\\abcd.xlsx");

book.Close();
app.Quit();

// 释放COM对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
>> 获取当前EXCEL表内容最后一行的编号(行数):   
        /// <summary>
        /// 获取EXCEL表内容行数
        /// </summary>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public int GetRowsCount(string sheetName)
        {

            Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.Worksheets[sheetName];           

            return worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Row;
        }

        注意: 如果EXCEL填充了背景色,即使里面没有内容也会被计算在内。

>> 如运行提示excel相关错误,需检查:Microsoft.Office.Interop.Excel组件是否正确添加引用,并设置为Embed interop Types ->Yes

>>参考: chttps://www.cnblogs.com/Asa-Zhu/archive/2012/12/06/2805021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值