學習-保存文件

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章