学习-保存文件

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();
        }

 

你可能感兴趣的:(PC)