当前位置: 代码迷 >> C# >> 用npoi如何在excel中插入一行
  详细解决方案

用npoi如何在excel中插入一行

热度:114   发布时间:2016-05-05 04:43:56.0
用npoi怎么在excel中插入一行
比如说,原本的excel是这样的:



现在我想在“名单”下面加一行日期,如



用npoi怎么插入啊??
用createRow不行。。。。
------解决思路----------------------
private void WriteExcel(string strPath)
        {
            ISheet sheet = null;
            NPOI.SS.UserModel.IWorkbook workbook = null;
            IRow row = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(strPath, FileMode.Open, FileAccess.Read);
                if (strPath.IndexOf(".xlsx") > 0) // 2007版本
                {
                    workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                }
                else if (strPath.IndexOf(".xls") > 0) // 2003版本
                {
                    workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                }

                if (workbook == null)
                {
                    return;
                }

                sheet = workbook.GetSheetAt(0);
                row = sheet.CopyRow(0, 1);
                row.CreateCell(0).SetCellValue(DateTime.Today.ToString("yyyy-MM-dd"));

                MemoryStream stream = new MemoryStream();
                workbook.Write(stream);
                var buf = stream.ToArray();

                fs = new FileStream(strPath, FileMode.Create, FileAccess.Write);
                fs.Write(buf, 0, buf.Length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Dispose();
                    fs.Close();
                }

                row = null;
                sheet = null;
                workbook = null;
            }
        }




  相关解决方案