C#导出数据到Excel模板and如何画Excel模板并导出数据,导入excel数据

首先,导出数据到Excel模板有两种方式:

一、使用Microsoft.Office.Interop.Excel组件的方式

二、使用NPOI的方式

一、使用Microsoft.Office.Interop.Excel组件的方式

该方式需要引入Microsoft.Office.Interop.Excel;System.Reflection

实现代码:

/// <summary>
/// 生成附件(使用Microsoft.Office.Interop.Excel组件的方式)
/// </summary>
/// <param name="DT"></param>
/// <returns></returns>
public static void GenerateAttachment(DataTable DT)
{
    try
    {
        //需要添加 Microsoft.Office.Interop.Excel引用 
        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        if (app == null)//服务器上缺少Excel组件,需要安装Office软件
        {
            return;
        }
        app.Visible = false;
        app.UserControl = true;
        string strTempPath = Application.StartupPath + "\\EmailTemplate\\TE Enrollment Form.xls";
        Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
        Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加载模板
        Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
        Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。
        if (worksheet == null)//工作薄中没有工作表
        {
            return;
        }

        //1、获取数据
        int rowCount = DT.Rows.Count;
        if (rowCount < 1)//没有取到数据
        {
            return;
        }

        //2、写入数据,Excel索引从1开始
        for (int i = 1; i <= rowCount; i++)
        {
            int row_ = 2 + i;  //Excel模板上表头占了1行
            int dt_row = i - 1; //dataTable的行是从0开始的 
            worksheet.Cells[row_, 1] = DT.Rows[dt_row]["Lastname_EN"].ToString();
            worksheet.Cells[row_, 2] = DT.Rows[dt_row]["Firstname_EN"].ToString();
            worksheet.Cells[row_, 3] = DT.Rows[dt_row]["namechinese"].ToString();
        }
        //调整Excel的样式。
        Microsoft.Office.Interop.Excel.Range rg = worksheet.Cells.get_Range("A3", worksheet.Cells[rowCount + 2, 32]);
        rg.Borders.LineStyle = 1; //单元格加边框
        worksheet.Columns.AutoFit(); //自动调整列宽

        //隐藏某一行
        //选中部分单元格,把选中的单元格所在的行的Hidden属性设为true
        //worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Hidden = true;

        //删除某一行
        worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
        

        //3、保存生成的Excel文件
        //Missing在System.Reflection命名空间下
        string savePath = Application.StartupPath + "\\Temp\\TEEnrollmentForm\\TE Enrollment Form.xls";
        workbook.SaveAs(savePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        //4、按顺序释放资源
        NAR(worksheet);
        NAR(sheets);
        NAR(workbook);
        NAR(workbooks);
        app.Quit();
        NAR(app);
    }
    catch (Exception ex)
    {
        WriteLog(ex.ToString());
    }
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="o"></param>
public static void NAR(object o)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
    }
    catch (Exception ex)
    {
        WriteLog(ex.ToString());
    }
    finally
    {
        o = null;
    }
}

二、使用NPOI的方式

该方式需要引用NPOI.dll

实现代码:

/// <summary>
/// ExportExcel(使用NPOI的方式)
/// </summary>
/// <param name="DT"></param>
public static void ExportExcel(DataTable DT)
{
    try
    {
        HSSFWorkbook hssfworkbookDown;
        string modelExlPath = Application.StartupPath + "\\EmailTemplate\\TE Enrollment Form.xls";
        if (File.Exists(modelExlPath) == false)//模板不存在
        {
            return;
        }
        using (FileStream file = new FileStream(modelExlPath, FileMode.Open, FileAccess.Read))
        {
            hssfworkbookDown = new HSSFWorkbook(file);
            file.Close();
        }
        if (DT.Rows.Count > 0)
        {
            WriterExcel(hssfworkbookDown, 0, DT);

            string filename = "TE Enrollment Form.xls";
            string strFilePath = Application.StartupPath + "\\Temp\\TEEnrollmentForm";
            if (Directory.Exists(strFilePath) == false)
            {
                Directory.CreateDirectory(strFilePath);
            }
            strFilePath = strFilePath + "\\" + filename;
            FileStream files = new FileStream(strFilePath, FileMode.Create);
            hssfworkbookDown.Write(files);
            files.Close();
            if (File.Exists(strFilePath) == false)//附件生成失败
            {
                return;
            }
        }
    }
    catch (Exception ex)
    {
        WriteLog(ex.ToString());
    }
}
/// <summary>
/// WriterExcel
/// </summary>
/// <param name="hssfworkbookDown"></param>
/// <param name="sheetIndex"></param>
/// <param name="DT"></param>
public static void WriterExcel(HSSFWorkbook hssfworkbookDown, int sheetIndex, DataTable DT)
{
    try
    {
        #region 设置单元格样式
        //字体
        HSSFFont fontS9 = (HSSFFont)hssfworkbookDown.CreateFont();
        fontS9.FontName = "Arial";
        fontS9.FontHeightInPoints = 10;
        fontS9.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.NORMAL;
        //表格
        ICellStyle TableS9 = (ICellStyle)hssfworkbookDown.CreateCellStyle();
        TableS9.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
        TableS9.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
        TableS9.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
        TableS9.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
        TableS9.WrapText = true;
        TableS9.SetFont(fontS9);
        #endregion

        HSSFSheet sheet = (HSSFSheet)hssfworkbookDown.GetSheetAt(sheetIndex);
        hssfworkbookDown.SetSheetHidden(sheetIndex, false);
        hssfworkbookDown.SetActiveSheet(sheetIndex);

        int n = 1;//因为模板有表头,所以从第2行开始写
        for (int j = 0; j < DT.Rows.Count; j++)
        {
            HSSFRow dataRow = (HSSFRow)sheet.CreateRow(j + n);
            string strDepID = DT.Rows[j]["relationship"].ToString().Trim();
            dataRow.CreateCell(0);
            dataRow.Cells[0].SetCellValue(strDepID == "" ? DT.Rows[j]["Lastname_EN"].ToString() : "");
            dataRow.CreateCell(1);
            dataRow.Cells[1].SetCellValue(strDepID == "" ? DT.Rows[j]["Firstname_EN"].ToString() : "");
            dataRow.CreateCell(2);
            dataRow.Cells[2].SetCellValue(strDepID == "" ? DT.Rows[j]["namechinese"].ToString() : "");

            for (int i = 0; i <= 2; i++)//循环列,添加样式
            {
                dataRow.Cells[i].CellStyle = TableS9;
            }
        }
        //设定第一行,第一列的单元格选中
        sheet.SetActiveCell(0, 0);
    }
    catch (Exception ex)
    {
        WriteLog(ex.ToString());
    }
}

三,手动画Excel

引用using org.in2bits.MyXls;

首先得把将要导出的数据转换为Datatable

然后创建Excel

        XlsDocument xls = new XlsDocument();//创建空xls文档
        xls.FileName = "D:\\" + UUIDGenerator.GetUUID() + ".xls";//保存路径,如果直接发送到客户端的话只需要名称 生成名称

        string[] cloName = { "序号", "部门ID", "部门", "人数", "预算分类", "分类金额", "单位", "预算(办公用品)", "预算(耗材)", "预算(打印纸)", "预算(其他)", "预算(物业物料)", "总预算额度" };
        ushort[] Clowidth = { 61 * 24, 400 * 24, 230 * 24, 100 * 24, 100 * 24, 100 * 24, 100 * 24, 150 * 24, 150 * 24, 150 * 24, 150 * 24, 150 * 24, 150 * 24 };
        string[] h = { "center", "left", "left", "center", "center", "right", "right", "right", "right", "right", "right", "right", "right" };

        Worksheet sheet = xls.Workbook.Worksheets.Add("部门预算分配"); //创建一个工作页为Dome
        //设置文档列属性 
        ColumnInfo cinfo;
        for (int j = 0; j < cloName.Length; j++)
        {
            cinfo = new ColumnInfo(xls, sheet);//设置xls文档的指定工作页的列属性
            cinfo.Collapsed = true;
            //设置列的范围 如 0列-10列
            cinfo.ColumnIndexStart = (ushort)j;//列开始
            cinfo.ColumnIndexEnd = (ushort)j;//列结束
            cinfo.Collapsed = true;
            cinfo.Width = Clowidth[j];//列宽度
            sheet.AddColumnInfo(cinfo);
        }
        //创建列样式创建列时引用
        XF cellXF = xls.NewXF();
        cellXF.VerticalAlignment = VerticalAlignments.Centered;
        cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
        cellXF.Font.Height = 24 * 12;
        cellXF.Font.Bold = true;
        cellXF.Pattern = 1;//设定单元格填充风格。如果设定为0,则是纯色填充
        cellXF.TextWrapRight = true;//单元格自动换行
        cellXF.PatternBackgroundColor = Colors.White;//填充的背景底色

        cellXF.PatternColor = Colors.White;//设定填充线条的颜色
        // 列标题样式 
        XF cellXFBTHeader = xls.NewXF();
        cellXFBTHeader.VerticalAlignment = VerticalAlignments.Centered;
        cellXFBTHeader.HorizontalAlignment = HorizontalAlignments.Centered;// 设定文字居中 
        cellXFBTHeader.UseBorder = true;
        cellXFBTHeader.Font.Bold = true;
        cellXFBTHeader.LeftLineStyle = 1; // 左边框样式  
        cellXFBTHeader.LeftLineColor = Colors.Black; // 左边框颜色  
        cellXFBTHeader.BottomLineStyle = 1;  // 下边框样式  
        cellXFBTHeader.BottomLineColor = Colors.Black;  // 下边框颜色 
        cellXFBTHeader.TopLineColor = Colors.Black;//上边框颜色
        cellXFBTHeader.TopLineStyle = 1;//上边样式
        cellXFBTHeader.RightLineStyle = 1;//右边样式
        cellXFBTHeader.RightLineColor = Colors.Black;//右边框颜色
        //cellXFBTHeader.Font.Height = 24 * 15;

        //列单元格样式
        XF cellXFBT = xls.NewXF();
        cellXFBT.VerticalAlignment = VerticalAlignments.Centered;
        // cellXFBT.HorizontalAlignment = HorizontalAlignments.Left;// 设定文字居左  
        cellXFBT.UseBorder = true;
        cellXFBT.LeftLineStyle = 1; // 左边框样式  
        cellXFBT.LeftLineColor = Colors.Black; // 左边框颜色  
        cellXFBT.BottomLineStyle = 1;  // 下边框样式  
        cellXFBT.BottomLineColor = Colors.Black;  // 下边框颜色 
        cellXFBT.TopLineColor = Colors.Black;//上边框颜色
        cellXFBT.TopLineStyle = 1;//上边样式
        cellXFBT.RightLineStyle = 1;//右边样式
        cellXFBT.RightLineColor = Colors.Black;//右边框颜色
        cellXFBT.TextWrapRight = true;//单元格自动换行

        //创建列样式结束
        //创建列
        Cells cells = sheet.Cells; //获得指定工作页列集合

        MergeRegion(ref sheet, cellXF, "部门预算分配", 1, 1, 2, cloName.Length);
        //创建列结束 

        //创建列表头
        for (int j = 0; j < cloName.Length; j++)
        {
            Cell TDtitle = cells.Add(3, j + 1, cloName[j], cellXFBTHeader);
        }
        for (int j = 0; j < dtOut.Rows.Count; j++)
        {
            for (int k = 0; k < cloName.Length; k++)
            {
                switch (h[k])
                {
                    case "center":
                        cellXFBT.HorizontalAlignment = HorizontalAlignments.Centered;
                        break;
                    case "left":
                        cellXFBT.HorizontalAlignment = HorizontalAlignments.Left;
                        break;
                    case "right":
                        cellXFBT.HorizontalAlignment = HorizontalAlignments.Right;
                        break;
                }
                if (k == 0)
                {
                    cells.Add(j + 4, k + 1, j + 1, cellXFBT);//添加列,不设置列属性就不用返回列对象
                }
                else
                {
                    cells.Add(j + 4, k + 1, dtOut.Rows[j][cloName[k]].ToString(), cellXFBT);//添加列,不设置列属性就不用返回列对象
                }
            }
        }

        //生成保存到服务器如果存在不会覆盖并且报异常所以先删除在保存新的
        //  sheet.Rows[1].RowHeight = 30 * 20;
        File.Delete(xls.FileName);//删除
        // xls.Save();//保存到服务器
        //xls.FileName = HttpUtility.UrlEncode("部门预算分配", System.Text.Encoding.UTF8);
        if (Request.UserAgent.Contains("MSIE") || Request.UserAgent.Contains("msie"))
        {
            xls.FileName = HttpUtility.UrlEncode("部门预算分配", System.Text.Encoding.UTF8);
        }
        else
        {
            xls.FileName = "部门预算分配.xls";
        }
        xls.Send();//发送到客户端



    }
    public void MergeRegion(ref Worksheet ws, XF xf, string title, int startRow, int startCol, int endRow, int endCol)
    {
        for (int i = startCol; i <= endCol; i++)
        {
            for (int j = startRow; j <= endRow; j++)
            {
                ws.Cells.Add(j, i, title, xf);
            }
        }
        ws.Cells.Merge(startRow, endRow, startCol, endCol);
    }

    

四,导入Excel数据

            HttpFileCollection httpFileCollection = context.Request.Files;
            HttpPostedFile exlfile = httpFileCollection[0]; //获取导入的Excel文件
            string filename = exlfile.FileName + DateTime.Now.ToString("yyyyMMddHHmmss");//获取导入的Excel文件名
            string savePath = System.Web.HttpContext.Current.Server.MapPath(("~\\FileUpdate\\") + filename);//Excel存取路径 加上日期,让excel文件名不重复
            exlfile.SaveAs(savePath);//将excel文件保存一下,可以找到文件可以删除
            string originData = context.Request["originData"];
            DataTable dtOrigin = JsonToDataTable(originData);//把发送页面数据转化为Datatable
            var bll = new cmcc_os_budget_sortBLL();//获取cmcc_os_budget_sort中的所有数据
            var list_sort = bll.GetListWhere(new StringBuilder(" and comp_code=@comp_code"), new SqlParam[] { new SqlParam("@comp_code", staff.CompPkid) }) as List<cmcc_os_budget_sort>;
            var notFoundList = new List<string>();
            using (FileStream file = new FileStream(savePath, FileMode.Open, FileAccess.Read))
            {
                HSSFWorkbook workbook = new HSSFWorkbook(file);//获取文件
                ISheet sheet = workbook.GetSheetAt(0); //获取文件的sheet
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();//得到所有行数据
                while (rows.MoveNext())//遍历每一行时
                {
                    IRow row = (HSSFRow)rows.Current;//当前行数据
                    if (row.RowNum <= sheet.FirstRowNum + 2)//如果是第一行 继续
                    {
                        continue;
                    }
                    if (row.Cells[0].ToString() == "")//如果第一列序号列为空(防止数据为空数据或者其他无关内容)
                        break;
                    //try
                    //{
                    //    double dd = row.Cells[0].NumericCellValue;//如果第一列序号列为非数字类型(防止数据为空数据或者其他无关内容)
                    //}
                    //catch
                    //{
                    //    break;
                    //}
                    //entity.pk_id = UUIDGenerator.GetUUID();
                    cmcc_os_organ_budget entity = new cmcc_os_organ_budget();

                    foreach (ICell item in sheet.GetRow(sheet.FirstRowNum + 2).Cells)//列名
                    {
                        if (item.ToString() == "部门ID")//如果此列为 产品大类  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.organ_pkid = null;
                            }
                            else
                            {
                                entity.organ_pkid = row.Cells[item.ColumnIndex].ToString();//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "人数")//如果此列为 产品中类  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.people_num = null;
                            }
                            else
                            {
                                entity.people_num = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString().Contains("预算分类"))//如果此列为 产品小类  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                // entity.budget_pkid = null;
                                entity.budget_sort = null;
                            }
                            else
                            {
                                // entity.budget_pkid = row.Cells[item.ColumnIndex].ToString();//取当前列 当前列名索引的值
                                entity.budget_sort = row.Cells[item.ColumnIndex].ToString();
                            }
                        }
                        else if (item.ToString() == "分类金额")//如果此列为 产品规格  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_sort_money = null;
                            }
                            else
                            {
                                entity.budget_sort_money = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "单位")//如果此列为 参考品牌  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.sort_money_unit = null;
                            }
                            else
                            {
                                entity.sort_money_unit = row.Cells[item.ColumnIndex].ToString();//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "预算(办公用品)")//如果此列为 供货产品名称  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_oa = null;
                            }
                            else
                            {
                                entity.budget_oa = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "预算(耗材)")//如果此列为 物料编码  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_cm = null;
                            }
                            else
                            {
                                entity.budget_cm = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "预算(打印纸)")//如果此列为 供货产品品牌型号  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_pp = null;
                            }
                            else
                            {
                                entity.budget_pp = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "预算(其他)")//如果此列为 报价单位  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_ot = null;
                            }
                            else
                            {
                                entity.budget_ot = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "预算(物业物料)")//如果此列为 报价单位  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_pm = null;
                            }
                            else
                            {
                                entity.budget_pm = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "总预算额度")//如果此列为 品牌原厂商  列
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.budget_money = null;
                            }
                            else
                            {

                                entity.budget_money = decimal.Parse(row.Cells[item.ColumnIndex].ToString());//取当前列 当前列名索引的值
                            }
                        }
                        else if (item.ToString() == "部门")
                        {
                            if (row.Cells[item.ColumnIndex].ToString() == "")
                            {
                                entity.modify_emp = null;
                            }
                            else
                            {

                                entity.modify_emp = row.Cells[item.ColumnIndex].ToString();//取当前列 当前列名索引的值
                            }
                        }
                    }
                    var rowsTemp = dtOrigin.Select(string.Format("organ_pkid='{0}'", entity.organ_pkid));
                    if (rowsTemp.Length > 0)
                    {
                        var t = rowsTemp[0];
                        t["people_num"] = entity.people_num;
                        t["budget_cm"] = entity.budget_cm;
                        t["budget_pp"] = entity.budget_pp;
                        t["budget_ot"] = entity.budget_ot;
                        t["budget_pm"] = entity.budget_pm;
                        var cmcc_os_budget_sort = list_sort.Find(l => l.budget_sort == entity.budget_sort);//t.organ_name.Equals("显示全部")
                        if (cmcc_os_budget_sort != null)
                        {
                            t["budget_sort"] = cmcc_os_budget_sort.budget_sort;
                            t["budget_pkid"] = cmcc_os_budget_sort.pk_id;
                            t["budget_sort_money"] = cmcc_os_budget_sort.budget_sort_money;
                            t["sort_money_unit"] = cmcc_os_budget_sort.sort_money_unit;
                        }
                        t["budget_oa"] = ToDecimal(t["people_num"]) * ToDecimal(t["budget_sort_money"]);
                        t["budget_money"] = ToDecimal(t["budget_oa"]) + ToDecimal(t["budget_cm"]) +
                            ToDecimal(t["budget_pp"]) + ToDecimal(t["budget_ot"]) + ToDecimal(t["budget_pm"]);//
                        t["rested_money"] = ToDecimal(t["budget_money"]) - ToDecimal(t["implemented_money"]);//剩余额度
                        t.AcceptChanges();
                    }
                    else
                    {
                        //notFoundList.Add(entity.organ_pkid);//organ_pkid:导入文件部门id
                        notFoundList.Add(entity.modify_emp);//modify_emp:导入部门名称
                        //上述2行2选1
                    }

                }
            


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值