其他分享
首页 > 其他分享> > 将Excel文件的导入与生成

将Excel文件的导入与生成

作者:互联网

这个是前端通过api将文件上传至api中做处理,在后端做文件解析和处理

<form id="form-avatar" enctype="multipart/form-data">
    <p>请选择要上传的文件:</p>
    <!--只能选择单个个文件-->
    <p><input type="file" name="file" /></p>
    <!--同时选择多个文件-->
    <p><input type="file" name="file" multiple="multiple" /></p>
    <p><input id="btn-avatar" type="button" value="上传" /></p>
</form>
<script>
$("#btn-avatar").click(function(){
    $.ajax({    
         url : "/api/values", //指定得api地址,当前环境得api地址
         data: new FormData($("#form-avatar")[0]),
         type : "POST",  
         // 告诉jQuery不要去处理发送的数据,用于对data参数进行序列化处理 这里必须false 
         processData : false,
         // 告诉jQuery不要去设置Content-Type请求头
         contentType : false,
         dataType:"json",  
         success : function(json) {    
          
         },    
         error : function(json) {    
         }    
    });
});
</script>

对应得Api,需要引用NPOI解析文件。(上传)

 public string Post()
        {
            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            //获取上传的文件
            StringBuilder sbr = new StringBuilder();
            Stream st = file.InputStream;
            IWorkbook wk = null;
            try
            {
                wk = new XSSFWorkbook(st);   //把xls文件中的数据写入wk中
            }
            catch {
                return "文件格式不正确";
            }

            for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
            {
                ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据
                for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                {
                    IRow row = sheet.GetRow(j);  //读取当前行数据
                    if (row != null)
                    {
                        sbr.Append("-------------------------------------\r\n"); //读取行与行之间的提示界限
                        for (int k = 0; k <= row.LastCellNum; k++)  //LastCellNum 是当前行的总列数
                        {
                            ICell cell = row.GetCell(k);  //当前表格
                            if (cell != null)
                            {
                                sbr.Append(cell.ToString());   //获取表格中的数据并转换为字符串类型
                            }
                        }
                    }
                }
            }
            //string url = HttpContext.Current.Server.MapPath(@"~\App_Data\") + file.FileName;//文件上传的位置
            //if (string.IsNullOrEmpty(file.FileName) == false)
            //file.SaveAs(url);保存文件
            ////读取上传的文件
            //StringBuilder sbr = new StringBuilder();
            //using (FileStream fs = File.OpenRead(url))  //打开Excel文件
            //{

            //}
            return sbr.ToString();//返回数据
        }

将数据库的文件导出显示在页面之中

//创建工作薄
            var workbook = new HSSFWorkbook();
            //创建表
            var table = workbook.CreateSheet("joye.net");

            //模拟20行20列数据
            for (var i = 0; i < 20; i++)
            {
                var row = table.CreateRow(i);
                for (int j = 0; j < 20; j++)
                {
                    var cell = row.CreateCell(j);
                    cell.SetCellValue(j);
                }
            }
            //打开xls文件,如没有则创建,如存在则在创建是不要打开该文件
            using (var fs = File.OpenWrite(@"c:/joye.net.xls"))
            {
                workbook.Write(fs);   //向打开的这个xls文件中写入mySheet表并保存。
                Console.WriteLine("生成成功");
            }

简单学习

/// <summary>
        ///  组装workbook.
        /// </summary>
        /// <param name="dt">dataTable资源</param>
        /// <param name="columnHeader">表头</param>
        /// <returns></returns>
        public static HSSFWorkbook BuildWorkbook1(DataTable dt, string columnHeader = "")
        {
            var workbook = new HSSFWorkbook();//创建工作铺
            ISheet sheet = workbook.CreateSheet(string.IsNullOrWhiteSpace(dt.TableName) ? "Sheet1" : dt.TableName);

            #region 文件属性信息
            {
                var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "NPOI";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = "文件作者信息";
                si.ApplicationName = "创建程序信息";
                si.LastAuthor = "最后保存者信息";
                si.Comments = "作者信息";
                si.Title = "标题信息";
                si.Subject = "主题信息";
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            var dateStyle = workbook.CreateCellStyle();//创建列样式
            var format = workbook.CreateDataFormat();//数据格式
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");//设置日期显示格式

            //取得列宽
            var arrColWidth = new int[dt.Columns.Count];
            foreach (DataColumn item in dt.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            //获取datatable的每行每列的数据显示成中文,在获取中文长度
            encoding编码文档:https://www.cnblogs.com/renfeng/p/4397592.html
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                for (var j = 0; j < dt.Columns.Count; j++)
                {
                    //Encoding.GetEncoding(936)解码
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dt.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dt.Rows)
            {
                #region 表头 列头
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }

                    #region 表头及样式
                    {
                        var headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(columnHeader);
                        //CellStyle
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;// 左右居中    
                        headStyle.VerticalAlignment = VerticalAlignment.Center;// 上下居中 
                        // 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)    
                        headStyle.FillForegroundColor = (short)11;
                        //定义font
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        headerRow.GetCell(0).CellStyle = headStyle;
                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));
                    }
                    #endregion


                    #region 列头及样式
                    {
                        var headerRow = sheet.CreateRow(1);
                        //CellStyle
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;// 左右居中    
                        headStyle.VerticalAlignment = VerticalAlignment.Center;// 上下居中 
                        //定义font
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        foreach (DataColumn column in dt.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                    }
                    #endregion
                    if (columnHeader != "")
                    {
                        //header row
                        IRow row0 = sheet.CreateRow(0);
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            ICell cell = row0.CreateCell(i, CellType.String);
                            cell.SetCellValue(dt.Columns[i].ColumnName);
                        }
                    }

                    rowIndex = 2;
                }
                #endregion


                #region 内容
                var dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dt.Columns)
                {
                    var newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }
            //自动列宽
            for (int i = 0; i <= dt.Columns.Count; i++)
                sheet.AutoSizeColumn(i, true);

            return workbook;
        }

参考文档

 

https://www.cnblogs.com/yinrq/p/5590970.html

标签:headStyle,Excel,System,生成,workbook,导入,var,dt,SetCellValue
来源: https://www.cnblogs.com/LanHai12/p/15258102.html