c# npoi 操作excel文件,将excel转txt
提取excel文件指定项,先将无用列删除,结果如图:
利用npoi库,nuget下载一键安装
代码如下:
private void button2_Click(object sender, EventArgs e)
{
List<string> elist = new List<string>();
using (FileStream fs = new FileStream(@"D:\Users\yaoyue\Desktop\2.xls", FileMode.Open, FileAccess.Read))
{
//从文件柄创建对象
HSSFWorkbook workbook = new HSSFWorkbook(fs);
//通过名称查找sheet
HSSFSheet hsheet = (HSSFSheet)workbook.GetSheet("sheet1");
//格式对象,用来格式化cell内容,一律返回字符串
DataFormatter df = new DataFormatter();
//遍历放入list
for (int i = 0; i < hsheet.LastRowNum; i++)
{
//FormatCellValue()格式化cell内容,返回其字符串
elist.Add($"题目{i} " + df.FormatCellValue(hsheet.GetRow(i).GetCell(1)));
elist.Add("A " + df.FormatCellValue(hsheet.GetRow(i).GetCell(3)));
elist.Add("B " + df.FormatCellValue(hsheet.GetRow(i).GetCell(4)));
//判断题排除c d空选项
if (!string.IsNullOrEmpty(df.FormatCellValue(hsheet.GetRow(i).GetCell(5))))
{
elist.Add("C " + df.FormatCellValue(hsheet.GetRow(i).GetCell(5)));
}
if (!string.IsNullOrEmpty(df.FormatCellValue(hsheet.GetRow(i).GetCell(6))))
{
elist.Add("D " + df.FormatCellValue(hsheet.GetRow(i).GetCell(6)));
}
elist.Add("答案 " + df.FormatCellValue(hsheet.GetRow(i).GetCell(2)));
}
}
//每个list元素占一行
File.WriteAllLines(@"D:\Users\yaoyue\Desktop\1.txt", elist.ToArray());
}
问题解答:
1. npoi 报错Cannot get a numeric value from a text cell 的解决
DataFormatter formatter2 = new DataFormatter(); //creating formatter using the default locale
ICell cell = sheet.GetRow(k).GetCell(l);
String j = formatter2.FormatCellValue(cell); //无视cell类型,返回字符串
结果如下
库基础请看:https://blog.csdn.net/jmh1996/article/details/78225718