>>创建保存:
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