Excel讀取和寫入的完整代碼using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using System;using System.IO; namespace ConsoleTest{ class ...
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("\n");
}
}
}
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);
}
}
}
}