C# Excel操作之读,写,追加

C# Excel追加数据

上一篇介绍了写Excel:写Excel
本篇介绍在Excel中追加数据:
追加数据除了写操作的功能外,还要注意流程和追加的位置。
此处使用xls作为模板追加数据,代码如下:

/// <summary>
        /// 在已有的Excel中追加数据
        /// </summary>
        /// <param name="template_file_path">           模板文件完整路径</param>
        /// <param name="output_file_path">             导出文件完整路径</param>
        /// <param name="dt">                           数据</param>
        /// <param name="sheet_name">                   Sheet名称</param>
        /// <param name="start_row">                    起始行</param>
        /// <returns>true 成功  false 失败</returns> 
        public bool Add_DataTable_To_Excel(string template_file_path, string output_file_path, DataTable dt, string sheet_name, int start_row)
        {
            string[] temp = template_file_path.Split('.');
            string[] temp1 = output_file_path.Split('.');
            if (temp[temp.Count() - 1] != temp1[temp1.Count() - 1])
            {
                Trace("file format error,inconsistent format");
                return false;
            }

            if (start_row < 1)
            {
                Trace("start row must bigger than 0");
                return false;
            }

            bool bxls = false;

            ISheet sheet = null;
            HSSFWorkbook hssfworkbook = null;
            XSSFWorkbook xssfworkbook = null;
            HSSFCellStyle cell_Style = null;

            try
            {
                if (File.Exists(output_file_path))
                    File.Delete(output_file_path);

                File.Copy(template_file_path, output_file_path);
            }
            catch (Exception ex)
            {
                Trace(ex.Message);
                return false;
            }

            FileStream file = new FileStream(output_file_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (temp[temp.Count() - 1].Equals("xlsx"))              // 2007版本  
            {
                xssfworkbook = new XSSFWorkbook();
                sheet = xssfworkbook.GetSheet(sheet_name);
            }
            else if (temp[temp.Count() - 1].Equals("xls"))          // 2003版本 
            {
                bxls = true;
                hssfworkbook = new HSSFWorkbook(file);
                sheet = hssfworkbook.GetSheet(sheet_name);

                //设置单元格格式
                cell_Style = (HSSFCellStyle)hssfworkbook.CreateCellStyle();                 //定义一个单元格样式 
                                                                                            // 设置单元格背景色 
                cell_Style.FillForegroundColor = HSSFColor.COLOR_NORMAL;                    //HSSFColor.Red.Index;
                cell_Style.FillPattern = FillPattern.SolidForeground;
                //设置文字对齐方式 
                cell_Style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;        //水平居中 
                cell_Style.VerticalAlignment = VerticalAlignment.Center;                    //垂直居中 
                                                                                            //设置字体格式开始 
                HSSFFont hssf_font = (HSSFFont)hssfworkbook.CreateFont();
                //设置字体的颜色为自定义颜色 
                HSSFPalette palette = hssfworkbook.GetCustomPalette();
                palette.SetColorAtIndex(HSSFColor.Lime.Index, (byte)0, (byte)0, (byte)0);   //RGB颜色值 
                hssf_font.Color = HSSFColor.Lime.Index;
                //字体属性 
                hssf_font.FontName = "微软雅黑";
                hssf_font.FontHeightInPoints = 10;                                          //设置字体大小 
                hssf_font.IsBold = true;
                cell_Style.SetFont(hssf_font);                                              //设置cellStyle 样式的字体 

                IDataFormat dataFormat = hssfworkbook.CreateDataFormat();                   //设置单元格格式
                cell_Style.DataFormat = dataFormat.GetFormat("@");
                //边框 
                cell_Style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;               //None 无边框     Thin 细线  Thick 粗线   
                cell_Style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;                 //Hair Dotted Dashed Medium 点状线
                cell_Style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;                //SlantedDashDot MediumDashDotDot DashDotDot MediumDashDot DashDot MediumDashed虚线
                cell_Style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;                  //Double双细线             
            }
            else
            {
                Trace("file format error,not excel file");
                return false;
            }

            file.Close();

            try
            {
                float output = 0.0f;
                IRow row = null;
                ICell cell = null;
                for (int i = 0; i < dt.Rows.Count; i++)             //数据
                {
                    row = sheet.CreateRow(i + 1 + start_row - 2);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        cell = row.CreateCell(j);

                        if (float.TryParse(dt.Rows[i][j].ToString(), out output))
                        {
                            cell.SetCellValue(Convert.ToDouble(output.ToString("0.00")));//输出数字
                        }
                        else
                            cell.SetCellValue(dt.Rows[i][j].ToString());

                        if (bxls)
                            cell.CellStyle = cell_Style;
                    }
                }

                MemoryStream stream = new MemoryStream();                   //转为字节数组
                if (temp[temp.Count() - 1].Equals("xlsx"))
                    xssfworkbook.Write(stream);
                else
                    hssfworkbook.Write(stream);

                var buf = stream.ToArray();

                using (FileStream fs = new FileStream(output_file_path, FileMode.Create, FileAccess.Write))        //保存为Excel文件
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                Trace(ex.Message);
                return false;
            }
            return true;
        }
        private void button_追加_Click(object sender, EventArgs e)
        {
            DataTable dt = Excel_To_DataTable("D:\\test.xlsx");

            Add_DataTable_To_Excel("D://test2.xls", "D://test3.xls", dt, "test", 10);
        }

追加数据
通过上图可以看到追加数据的效果!

在此强调一下此句:cell.SetCellValue(Convert.ToDouble(output.ToString(“0.00”)));//输出数字
如果不使用此句,导出的数字会出现批注,like this:
批注!

至此在Excel中追加数据的功能完成!
本人C#开发经验不足,有任何问题和可升级的部分请帮忙指出!

下载地址:完整代码

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值