• NOPI 读与写


    Excel读取和写入的完整代码
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System;
    using System.IO;

    namespace ConsoleTest
    {
    class Program
    {
    static void Main(string[] args)
    {
    //ReadFromExcelFile(@"H:班级文件(15软件)15级软件工程班名单.xls");
    WriteToExcel(@"H:班级文件(15软件)15级软件工程班名单1.xls");
    Console.ReadKey();
    }
    public static void ReadFromExcelFile(string filePath)
    {
    IWorkbook wk = null;
    string extension = System.IO.Path.GetExtension(filePath);
    try
    {
    using (FileStream fs = File.OpenRead(filePath))
    {
    if (extension.Equals(".xls"))
    {
    //把xls文件中的数据写入wk中
    wk = WorkbookFactory.Create(fs);//new HSSFWorkbook(fs);
    }
    else
    {
    //把xlsx文件中的数据写入wk中
    wk = WorkbookFactory.Create(fs);//new XSSFWorkbook(fs);
    }
    }
    //读取当前表数据
    ISheet sheet = wk.GetSheetAt(0);
    IRow row = sheet.GetRow(0); //读取当前行数据
    int offset = 0;
    int lastRowNum = sheet.LastRowNum;//LastRowNum 是当前表的总行数-1(注意)
    for (int i = 0; i <= lastRowNum; i++)
    {
    row = sheet.GetRow(i); //读取当前行数据
    if (row != null)
    {
    int lastCellNum= row.LastCellNum;
    //LastCellNum 是当前行的总列数
    for (int j = 0; j < lastCellNum; j++)
    {
    //读取该行的第j列数据
    string value = row.GetCell(j).ToString();
    Console.Write(value.ToString() + " ");
    }
    Console.WriteLine(" ");
    }
    }
    }
    catch (Exception e)
    {
    //只在Debug模式下才输出
    Console.WriteLine(e.Message);
    }
    }
    public static void WriteToExcel(string filePath)
    {
    using (Stream fileStream = File.OpenWrite(filePath))
    {
    IWorkbook wb = new XSSFWorkbook();//如果生成xls则是HSSFWorkbook
    ISheet sheet = wb.CreateSheet();
    IRow row = sheet.CreateRow(0);//0行号
    row.CreateCell(0).SetCellValue("rupeng");
    row.CreateCell(1).SetCellValue(3.14);
    wb.Write(fileStream);
    }

    }
    }
    }

  • 相关阅读:
    jqGrid基本使用
    模块熟悉
    正则表达式-精髓
    登录+购物车+信息保存
    输入打开文件
    python打印目录下的文件名
    进度条
    模块导入
    正则表达式
    函数笔记
  • 原文地址:https://www.cnblogs.com/Lee-wlog/p/11391277.html
Copyright © 2020-2023  润新知