NOPI用模板生成excel

来源:互联网 发布:idea mac 激活服务器 编辑:程序博客网 时间:2024/06/05 20:18

 

  private void btnCopy_Click(object sender, EventArgs e)
        {
            try
            {

               //Excel模板的路径
                FileStream file = new FileStream(@"e:/book1.xls", FileMode.Open, FileAccess.Read);

                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                Sheet sheet1 = hssfworkbook.GetSheet("Sheet1");
                //sheet1.CreateRow(3).CreateCell(3).SetCellValue(12345);
                //string value1=sheet1.GetRow(1).GetCell(1).ToString();
                //sheet1.GetRow(2).GetCell(1).SetCellValue(true);
                //sheet1.GetRow(1).GetCell(1).SetCellValue("Chen");
                //sheet1.GetRow(1).GetCell(1).SetCellValue("sss");
                //sheet1.GetRow(1).GetCell(1).SetCellValue("1111");
                //sheet1.GetRow(2).GetCell(1).SetCellValue(300);
               //Force excel to recalculate all the formula while open
                sheet1.ForceFormulaRecalculation = true;

                if (File.Exists(@"e:/test.xls"))
                {
                    File.Delete(@"e:/test.xls");

                }
                else
                {
                    FileStream file2 = new FileStream(@"e:/test.xls", FileMode.Create);
                    hssfworkbook.Write(file2);
                    file2.Close();
                }
                file.Close();
                MessageBox.Show("SUC");
            }
            catch(Exception ex)
            {
                MessageBox.Show("ERR");
            }
        }

其中需要注意的地方时:1,,如果模板中赋值过的地方再次赋值:sheet1.GetRow(2).GetCell(1).SetCellValue(true);

                                             2,如果没有赋值,为空的地方:sheet1.CreateRow(3).CreateCell(3).SetCellValue(12345);