.net 生成Excel并保存


 void SaveQuestionToExcel(List datas, string path)
        {

            using (Workbook workbook = new HSSFWorkbook())
            {
                var sheet = workbook.CreateSheet();
                //表格头样式
                CellStyle headerStyle = workbook.CreateCellStyle();
                Font newFont = workbook.CreateFont();

                newFont.Boldweight = short.MaxValue;
                newFont.FontHeightInPoints = 12;

                headerStyle.SetFont(newFont);
                headerStyle.Alignment = HorizontalAlignment.CENTER;
                headerStyle.FillPattern = FillPatternType.NO_FILL;

                HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);

                headerRow.CreateCell(0).SetCellValue("题型");
                headerRow.CreateCell(1).SetCellValue("试题内容");
                headerRow.CreateCell(2).SetCellValue("试题答案");
                headerRow.CreateCell(3).SetCellValue("难易度");
                headerRow.CreateCell(4).SetCellValue("文件夹");
                headerRow.CreateCell(5).SetCellValue("试题解析");


                headerRow.Cells.ForEach(x => x.CellStyle = headerStyle);

                int rowIndex = 1;
                foreach (var quesItem in datas)
                {

                    HSSFRow row = (HSSFRow)sheet.CreateRow(rowIndex);
                    row.CreateCell(0).SetCellValue(quesItem.QuestionType);
                    row.CreateCell(1).SetCellValue(quesItem.ContentText);
                    row.CreateCell(2).SetCellValue(quesItem.AnswerText);
                    row.CreateCell(3).SetCellValue(((HardLevelEnum)quesItem.HardLevel).GetText());
                    row.CreateCell(4).SetCellValue(quesItem.FolderFullPath);
                    row.CreateCell(5).SetCellValue(quesItem.AnalysisText);

                    rowIndex++;
                }

                for (int i = 0; i < 6; i++)
                {
                    sheet.AutoSizeColumn(i);

                }
                FileStream streamFile = new FileStream(path, FileMode.Create);
                MemoryStream streamMemory = new MemoryStream();

                workbook.Write(streamMemory);
                byte[] data = streamMemory.ToArray();
                streamFile.Write(data, 0, data.Length);

                // 清空缓冲区、关闭流
                streamFile.Flush();
                streamFile.Close();

                streamMemory.Close();
                streamMemory.Dispose();
            }
        }