菜的像徐坤
排名
7
文章
192
粉丝
15
评论
16
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

文件路径问题

4566人阅读 2021/11/3 17:19 总访问:973587 评论:0 收藏:0 手机
分类: 文件流

前言

提供手动选择路径的功能

保存文件的时候路径理论上不写死,需要用户手动选择保存路径

借助 FolderBrowserDialog 类


具体代码

  1.         /// <summary>
  2.         /// 文件路径
  3.         /// </summary>
  4.         string defaultPath = "";
  5.         
  6.         
  7.             FolderBrowserDialog fbd = new FolderBrowserDialog();
  8.             fbd.Description = "请选择文件下载地址";
  9.             //首次defaultPath为空,按FolderBrowserDialog默认设置(即桌面)选择  
  10.             if (defaultPath != "")
  11.             {
  12.                 //设置此次默认目录为上一次选中目录  
  13.                 fbd.SelectedPath = defaultPath;
  14.             }
  15.             //按下确定选择的按钮  
  16.             if (fbd.ShowDialog() == DialogResult.OK)
  17.             {
  18.                 //记录选中的目录  
  19.                 defaultPath = fbd.SelectedPath;
  20.             }
  21.             else
  22.             {
  23.                 return;
  24.             }
  25.             
  26.             
  27.       //查库
  28.             BaseDataEntities baseDataEntities = new BaseDataEntities();
  29.             List<JBYZDML> dataTable =  baseDataEntities.JBYZDML.ToList();
  30.             //内存中构建一个Exel
  31.             HSSFWorkbook workbook = new HSSFWorkbook();
  32.             //构建一个空的Exel表
  33.             HSSFSheet sheet = workbook.CreateSheet("学生信息表"as HSSFSheet;
  34.             //添加行(第一行)
  35.             HSSFRow row = sheet.CreateRow(0as HSSFRow;
  36.             //添加列(填充数据)(第一列)
  37.             HSSFCell num = row.CreateCell(0as HSSFCell;
  38.             num.SetCellValue("Code");
  39.             HSSFCell num1 = row.CreateCell(1as HSSFCell;
  40.             num.SetCellValue("Name");
  41.             foreach (JBYZDML item in dataTable)
  42.             {
  43.                 //添加列(填充数据)(第一列)
  44.                 HSSFCell rows1 = row.CreateCell(0as HSSFCell;
  45.                 num.SetCellValue(item.ZDDM);
  46.                 HSSFCell rows2 = row.CreateCell(1as HSSFCell;
  47.                 num.SetCellValue(item.ZDMC);
  48.             }
  49.             try
  50.             {
  51.                 defaultPath = defaultPath + @"\\" + Guid.NewGuid().ToString().Replace(" - """) + ".xlsx";
  52.                 //将内存中的数据写入磁盘
  53.                 using (FileStream filestream = new FileStream(defaultPath, FileMode.Create))
  54.                 {
  55.                     workbook.Write(filestream);
  56.                     filestream.Close();
  57.                 }
  58.             }
  59.             catch (Exception ex)
  60.             {
  61.                 Console.Write(ex);
  62.             }
  63.             MessageBox.Show("保存成功!");
  64.         }


评价