本文主要是介绍学习-保存文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
private void button_Click(object sender, EventArgs e){if (!File.Exists(fileName)){MessageBox.Show("请重启软件!");return;}FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);// 读取流fs.Seek(0, SeekOrigin.Begin);POIFSFileSystem ps = new POIFSFileSystem(fs);// 需using NPOI.POIFS.FileSystem;IWorkbook workbook = new HSSFWorkbook(ps);ISheet sheet = workbook.GetSheetAt(0); // 获取工作表IRow row = sheet.GetRow(1); // 得到表头row = sheet.CreateRow((sheet.LastRowNum + 1));// 在工作表中添加一行ICell cell = row.CreateCell(0);// 创建单元格样式ICellStyle cellStyle = workbook.CreateCellStyle();cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;// 对齐cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;// 设置字体IFont font = workbook.CreateFont();font.FontHeightInPoints = 18;font.FontName = "微软雅黑";cellStyle.SetFont(font);string strDate = tb_date.Text;string strSN = tb_sn.Text;string strDefectCode = cb_defectCode.Text;string strArea = ((Button)sender).Text.Substring(4);//设置值cell = row.CreateCell(0);cell.SetCellValue(strDate);cell.CellStyle = cellStyle;cell = row.CreateCell(1);cell.SetCellValue(strSN);cell.CellStyle = cellStyle;cell = row.CreateCell(2);cell.SetCellValue(strDefectCode);cell.CellStyle = cellStyle;cell = row.CreateCell(3);cell.SetCellValue(strArea);cell.CellStyle = cellStyle;m_workbook = workbook;WriteToFile();}
static void WriteToFile(){FileStream fout = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);// 写入流fout.Flush();m_workbook.Write(fout);//写入文件m_workbook = null;fout.Close();}
这篇关于学习-保存文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!