我正在尝试将excel文件导入到类列表(CLA)。 Excel工作表就像一个表,第一行有对象的名称,第一列和第二列也有特定的名称。每个单元格都有相应的3个名称和一个值。
如果单元格为null,则它将被跳过List。但是在分组中会出现NullException。
public class ImportFile
{
public HSSFWorkbook Workbook;
public ISheet Sheet;
public List<List<Cla>> ImportResult;
public ImportFile(string a)
{
try
{
using (FileStream file = new FileStream(a, FileMode.Open, FileAccess.Read))
{
Workbook = new HSSFWorkbook(file);
}
string sname = Workbook.GetSheetName(0);
Sheet = Workbook.GetSheet(sname);
int z = Sheet.PhysicalNumberOfRows; // RowNum - 1 : 0-s, Z-2
int x = Sheet.GetRow(0).PhysicalNumberOfCells; //ColNum -1 : 0-s, X-3
List<Cla> Clsit = new List<Cla>();
for (int i = 2; i <= x - 1; i++)
{
for (int j = 1; j <= z - 1; j++)
{
if (ClMaker(i, j, Sheet) != null)
{
Clsit.Add(ClMaker(j, i, Sheet));
}
}
}
ImportResult = Clsit.GroupBy(item => new { item.PriznakName, item.ClassNumber }).Select(group => group.ToList()).ToList(); //right here
}
catch (IOException)
{
MessageBox.Show("File is using");
}
}
public Cla ClMaker(int a, int b, ISheet c)
{
string name;
double value;
string pname;
string cln;
Cla Cl;
if(c.GetRow(a).GetCell(b) == null)
{
Cl = null;
return Cl;
}
else
{
value = c.GetRow(a).GetCell(b).NumericCellValue;
name = c.GetRow(a).GetCell(0).StringCellValue;
pname = c.GetRow(0).GetCell(b).StringCellValue;
cln = c.GetRow(a).GetCell(1).NumericCellValue.ToString();
Cl = new Cla(name, value, pname, cln);
return Cl;
}
}
}