NPOI导出完美合并单元格

后台:

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using NPOI.SS.UserModel;
using System.Web;
using NPOI.SS.Util;

public partial class toExecl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string riqi = "无";
            if (Request.QueryString["riqi"] != string.Empty)
            {
                riqi = Request.QueryString["riqi"];
            }
            DataTable dt = newdata(riqi);
            NpoiExcel(dt, riqi + "报表");
        }
    }
          public void NpoiExcel(DataTable dt, string title)
    {
        NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
        NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
        NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);
        ICellStyle style = book.CreateCellStyle();
        //添加列名
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            ICell cell = headerrow.CreateCell(i);
            cell.CellStyle = style;
            cell.SetCellValue(dt.Columns[i].ColumnName);
        }
        //添加第一行数据
        IRow row = sheet.CreateRow(1);
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            string cellText = dt.Rows[0][j].ToString();
            row.CreateCell(j).SetCellValue(cellText);
        }
        //从第二行开始循环,和上一行进行判断,如果相同,则合并
        for (int i = 1; i < dt.Rows.Count; i++)
        {
            row = sheet.CreateRow(i + 1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string cellText = dt.Rows[i][j].ToString();
                row.CreateCell(j).SetCellValue(cellText);
                string temp = dt.Rows[i - 1][j].ToString();
                //temp上一行数据,一定要判断是否为空!!!j< dt.Columns.Count-7,不需要合并的列,也可以改成 && (j!=5 || j!=7)
                if (!string.IsNullOrEmpty(temp) && cellText== temp && j< dt.Columns.Count-7)
                {
                    //本行和上一行合并,为什么是 i和i+1,这里是从第几行开始合并,到第几行结束,i是在dt里的行数,而在表里,因为有表头,所以必须要加1
                    CellRangeAddress region = new CellRangeAddress(i, i+1, j, j);
                    sheet.AddMergedRegion(region);
                }
            }
        }
        style.Alignment = HorizontalAlignment.Center;
        style.VerticalAlignment = VerticalAlignment.Center;
        MemoryStream ms = new MemoryStream();
        book.Write(ms);
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
        System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
        System.Web.HttpContext.Current.Response.End();
        book = null;
        ms.Close();
        ms.Dispose();
    }
    public DataTable newdata(string riqi)
    {
        DataSet ds = new DataSet();
        string mysql = "";
        if (riqi != "无")
        {
            mysql = "SELECT riqi,dhkhmc,fph,kpkhmc,cpmc,cpgg,zhang,KG,yuanzhang,yuanKG,xsje,hly,fkfs FROM KF_anyue('" + riqi + "')";  //表名和字段名也看着改
        }
        DataTable table = new DataTable();

        string connsql = ConfigurationManager.ConnectionStrings["CQJBB"].ToString();
        SqlConnection conn = new SqlConnection(connsql);
        try
        {
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(mysql, conn);
            da.Fill(ds);
            table = ds.Tables[0];
            conn.Close();
            conn.Dispose();
        }
        catch (Exception ex)
        {

        }
        table.Columns["riqi"].ColumnName = "日期";
        table.Columns["dhkhmc"].ColumnName = "订货客户名称";
        table.Columns["fph"].ColumnName = "发票号";
        table.Columns["kpkhmc"].ColumnName = "开票客户名称";
        table.Columns["cpmc"].ColumnName = "产品名称";
        table.Columns["cpgg"].ColumnName = "产品规格";
        table.Columns["zhang"].ColumnName = "张";
        table.Columns["KG"].ColumnName = "KG";
        table.Columns["yuanzhang"].ColumnName = "元张";
        table.Columns["yuanKG"].ColumnName = "元KG";
        table.Columns["xsje"].ColumnName = "销售金额";
        table.Columns["hly"].ColumnName = "回笼元";
        table.Columns["fkfs"].ColumnName = "付款方式";
        return table;
    }
}


前台是默认建立的空白aspx页面

调用------》toExecl.aspx?riqi=



你可能感兴趣的:(c#相关)