C#通过NPOI导入导出数据EXCEL
本文实例为大家分享了C#通过NPOI导入导出数据EXCEL的具体代码,供大家参考,具体内容如下
其实从数据库到服务器导入导出有很多方法,但是比较简单的有NPOI这个方法
准备工作,先增加到相应的lib,同时引用相关的dll
第一从数据库导出数据到Excel里面
首先我设置一个win窗体
第二步写代码
private void button1_Click(object sender, EventArgs e) { //查询数据,显示到表格上 ManagerInfoBll miBll = new ManagerInfoBll(); var list = miBll.GetList(); dataGridView1.DataSource = list; //进行excel 生成创建操作 //1 创建workboook ,不指定参数,表示创建一个新的工作本 HSSFWorkbook workbook = new HSSFWorkbook(); //2创建sheet HSSFSheet sheet = workbook.CreateSheet("管理员"); //3创建row HSSFRow row = sheet.CreateRow(0); //4创建cell HSSFCell cell0 = row.CreateCell(0); cell0.SetCellValue("管理员表"); //5设置合并单元格 sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(0, 0, 0, 3)); //6设置居中 HSSFCellStyle styleTitle = workbook.CreateCellStyle(); styleTitle.Alignment = 2; cell0.CellStyle = styleTitle; //6.1设置字体 HSSFFont fontTitle = workbook.CreateFont(); fontTitle.FontHeightInPoints = 14; styleTitle.SetFont(fontTitle); //7创建标题行 //7.1创建行 HSSFRow rowTitle = sheet.CreateRow(1); //7.2创建单元格 HSSFCell cellTitle0 = rowTitle.CreateCell(0); cellTitle0.SetCellValue("编号"); cellTitle0.CellStyle = styleTitle; HSSFCell cellTitle1 = rowTitle.CreateCell(1); cellTitle1.SetCellValue("姓名"); cellTitle1.CellStyle = styleTitle; HSSFCell cellTitle2 = rowTitle.CreateCell(2); cellTitle2.SetCellValue("密码"); cellTitle2.CellStyle = styleTitle; HSSFCell cellTitle3 = rowTitle.CreateCell(3); cellTitle3.SetCellValue("类型"); cellTitle3.CellStyle = styleTitle; int rowIndex = 2; //8.1遍历集合 foreach (var mi in list) {//8.2创建行 HSSFRow rowData = sheet.CreateRow(rowIndex++); //8.3创建单元格 HSSFCell cellData0 = rowData.CreateCell(0); cellData0.SetCellValue(mi.MId); HSSFCell cellData1 = rowData.CreateCell(1); cellData1.SetCellValue(mi.MName); HSSFCell cellData2 = rowData.CreateCell(2); cellData2.SetCellValue(mi.MPwd); HSSFCell cellData3 = rowData.CreateCell(3); cellData0.SetCellValue(mi.MType==1?"经理":"店员"); } //8 保持文本 FileStream stream = new FileStream("", FileMode.Create); workbook.Write(stream);// stream.Close(); stream.Dispose(); }
最后效果
第二从Excel导入到数据库中
private void button2_Click(object sender, EventArgs e) { //1读取excel 数据,存入list List<ManagerInfo> list = new List<ManagerInfo>(); //1.1读取文件 路径 using (FileStream stream= new FileStream("",FileMode.Open)) { //1.2创建workbook HSSFWorkbook workbook = new HSSFWorkbook(stream); //1.3读取sheet HSSFSheet sheet = workbook.GetSheetAt(0); //1.4读取正文数据主要从表格开始看起 第三行开始 int rowindex = 2; HSSFRow row = sheet.GetRow(10); while ( row==null) { //1.5读到数据返回行对象 ManagerInfo mi = new ManagerInfo(); mi.MId = (int)row.GetCell(0).NumericCellValue; mi.MName = row.GetCell(1).StringCellValue; mi.MPwd = row.GetCell(2).StringCellValue; mi.MType=row.GetCell(3).StringCellValue=="经理"?1 : 0; list.Add(mi); row = sheet.GetRow(rowindex++); } } //2将list赋值给dataGridview dataGridView1.DataSource = list; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)