简单介绍:
描述工作簿的类:Workbook(接口)、HSSFWorkbook(具体实现类)
描述工作表的类:Sheet(接口)、HSSFSheet(具体实现类)
读文件:
static void Main(string[] args)
{
FileStream fs;
try
{
fs = new FileStream(@"F:\1月30日\ppt\ReadExcel.xls", FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
return;
}
using (HSSFWorkbook workbook = new HSSFWorkbook(fs))//传递一个文件流
{
Sheet sheet = workbook.GetSheetAt(0);//根据索引获得第一个sheet
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= sheet.LastRowNum; i++)//sheet.LastRowNum属性获得的行号是以0为下标的
{//
for (int j = 0; j < sheet.GetRow(i).LastCellNum; j++)//LastCellNum属性获得的单元格号是以1为下标的
{
sb.Append(string.Format("{0}行,{1}列:{2}", i, j, sheet.GetRow(i).GetCell(j)));
sb.AppendLine();
}
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
}
写文件:
FileStream fs = new FileStream(@"C:\1.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (HSSFWorkbook workbook = new HSSFWorkbook())
{
using (Sheet sheet = workbook.CreateSheet())
{
for (int i = 0; i < 10; i++)
{
Row row = sheet.CreateRow(i);
for (int j = 0; j < 10; j++)
{
Cell cell= row.CreateCell(j);
cell.SetCellType(CellType.STRING);
cell.SetCellValue(string.Format("第{0}行,第{1}列",i,j));
}
}
workbook.Write(fs);
}
} |