文件路径问题
电脑版发表于:2021/11/3 17:19
前言
提供手动选择路径的功能
保存文件的时候路径理论上不写死,需要用户手动选择保存路径
借助 FolderBrowserDialog 类
具体代码
/// <summary> /// 文件路径 /// </summary> string defaultPath = ""; FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "请选择文件下载地址"; //首次defaultPath为空,按FolderBrowserDialog默认设置(即桌面)选择 if (defaultPath != "") { //设置此次默认目录为上一次选中目录 fbd.SelectedPath = defaultPath; } //按下确定选择的按钮 if (fbd.ShowDialog() == DialogResult.OK) { //记录选中的目录 defaultPath = fbd.SelectedPath; } else { return; } //查库 BaseDataEntities baseDataEntities = new BaseDataEntities(); List<JBYZDML> dataTable = baseDataEntities.JBYZDML.ToList(); //内存中构建一个Exel HSSFWorkbook workbook = new HSSFWorkbook(); //构建一个空的Exel表 HSSFSheet sheet = workbook.CreateSheet("学生信息表") as HSSFSheet; //添加行(第一行) HSSFRow row = sheet.CreateRow(0) as HSSFRow; //添加列(填充数据)(第一列) HSSFCell num = row.CreateCell(0) as HSSFCell; num.SetCellValue("Code"); HSSFCell num1 = row.CreateCell(1) as HSSFCell; num.SetCellValue("Name"); foreach (JBYZDML item in dataTable) { //添加列(填充数据)(第一列) HSSFCell rows1 = row.CreateCell(0) as HSSFCell; num.SetCellValue(item.ZDDM); HSSFCell rows2 = row.CreateCell(1) as HSSFCell; num.SetCellValue(item.ZDMC); } try { defaultPath = defaultPath + @"\\" + Guid.NewGuid().ToString().Replace(" - ", "") + ".xlsx"; //将内存中的数据写入磁盘 using (FileStream filestream = new FileStream(defaultPath, FileMode.Create)) { workbook.Write(filestream); filestream.Close(); } } catch (Exception ex) { Console.Write(ex); } MessageBox.Show("保存成功!"); }