Excel导入数据库
using (Stream stream = File.Open(@"E:\10级net3班信息表.xls", FileMode.Open, FileAccess.Read))//建立流,指向要读取的文件
{
HSSFWorkbook workbook = new HSSFWorkbook(stream);
HSSFSheet sheet = workbook.GetSheet("10级net3班联系表");
excelthreelayer.bll.T_classmessage bstudent = new excelthreelayer.bll.T_classmessage();
//遍历所有行,LastRowNum是最后一行的索引,而不是总的行数,总的行数应该是LastRowNum+1,所以下面使用i<=sheet.LastRowNum或者i<LastRowNum+1
List<excelthreelayer.model.T_classmessage> list = new List<excelthreelayer.model.T_classmessage>();
for (int i = 1; i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i);//获取行
excelthreelayer.model.T_classmessage minfo = new excelthreelayer.model.T_classmessage();
minfo.classname = row.GetCell(0).StringCellValue;
minfo.userid = row.GetCell(1).StringCellValue;
minfo.username = row.GetCell(2).StringCellValue;
minfo.tel = row.GetCell(3).StringCellValue;
minfo.QQ = row.GetCell(4).StringCellValue;
list.Add(minfo);
}
bstudent.Add1(list);
MessageBox.Show("操作成功");
}
将数据库的表信息导入Excel文件
excelthreelayer.bll.T_classmessage b = new excelthreelayer.bll.T_classmessage();
int maxid = b.GetMaxId();
using (FileStream stream = new FileStream(@"d:\2010级net班信息表.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))//建立文件写入流
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet("net班信息表");
sheet.CreateRow(0).CreateCell(0).SetCellValue("编号");//添加表头
sheet.CreateRow(0).CreateCell(1).SetCellValue("班级名称");
sheet.CreateRow(0).CreateCell(2).SetCellValue("学号");
sheet.CreateRow(0).CreateCell(3).SetCellValue("姓名");
sheet.CreateRow(0).CreateCell(4).SetCellValue("电话");
sheet.CreateRow(0).CreateCell(5).SetCellValue("QQ");
for (int i = 1; i < maxid; i++)
{
excelthreelayer.model.T_classmessage model = b.GetModel(i);//利用方法得到数据行的数据
HSSFRow row = sheet.CreateRow(i);
row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.id);
row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.classname);
row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.userid);
row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.username);
row.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.tel);
row.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue(model.QQ);
}
workbook.Write(stream);//写入文件流
}