NPOI

https://archive.codeplex.com/?p=npoi

NPOI下载官网http://npoi.codeplex.com

下载解压,里面有个dotnet4的文件夹,把它拖到自己的项目中,把里面的.dll全部添加引用


基础概念

excel2007:xlsx

XSSFWorkbook wb;
XSSFSheet sh;

excel2003 :xls

HSSFWorkbook wk = new HSSFWorkbook();
ISheet sheet = wk.CreateSheet("Images");

IRow dataRow = confidence_sheet.CreateRow(i);
ICell  cell = dataRow.CreateCell(j);
ICellStyle cellstyle = workbook.CreateCellStyle();
cellstyle.VerticalAlignment = VerticalAlignment.Center;
cellstyle.Alignment = HorizontalAlignment.Center;
cell.CellStyle = cellstyle;

读取现有的Excel

HSSFWorkbook wb;
FileStream file;
file = new FileStream(filepath, FileMode.Open, FileAccess.Read);
wb = new HSSFWorkbook(file);
file.Close();
// 获取已有表
ISheet image_sheet = wk.GetSheet("Images");
ISheet confidence_sheet = wk.GetSheet("Confidence");
int rowsCount = image_sheet .PhysicalNumberOfRows; //取行Excel的最大行数
int colsCount = image_sheet .GetRow(0).PhysicalNumberOfCells;//取得Excel的列数

 


C# 使用NPOI操作Excel文件


c#开源Excel操作库–NPOI


使用Npoi向Excel中插入图片


 


using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream fs = File.OpenRead(@"F:\\PycharmWorkPlace\\test2excel\\test.xlsx"))   //打开myxls.xls文件{
            {
                
                XSSFWorkbook wb = new XSSFWorkbook(fs);
               // HSSFWorkbook wk = new HSSFWorkbook(fs);
                ISheet sh = wb.GetSheet("Sheet1");
                Console.WriteLine(sh.GetRow(0).GetCell(0).StringCellValue);
                Console.ReadLine();




            }

        }
    }
}