代码之家  ›  专栏  ›  技术社区  ›  BellHopByDayAmetuerCoderByNigh

将文件名和位置从SaveFileDialog传递给变量

  •  0
  • BellHopByDayAmetuerCoderByNigh  · 技术社区  · 8 年前

    ToExcel() 知道文件名和保存位置的方法?

    private void btnSave_Click(object sender, EventArgs e)
    {
        //Creating Save File Dialog
        SaveFileDialog save = new SaveFileDialog();
        //Showing the dialog
        save.ShowDialog();
        //Setting default directory
        save.InitialDirectory = @"C:\";
        save.RestoreDirectory = true;
        //Setting title
        save.Title = "Select save location and input file name";
        //filtering to only show .xml files in the directory
        save.DefaultExt = "xml";
        //Write Data To Excel
        ToExcel();
    }
    
    private void ToExcel()
    {
        var file = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Test_" + DateTime.Now.ToString("M-dd-yyyy-HH.mm.ss") + ".xlsx"));
    
        using (var package = new ExcelPackage(file))
        {
            ExcelWorksheet ws = package.Workbook.Worksheets.Add("Test");
            ws.Cells[1, 1].Value = "One";
            ws.Cells["A1:C1"].Style.Font.Bold = true;
            package.Save();
            MessageBox.Show("Saved!");
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   MikeT    8 年前

    首先 ShowDialog 应该是您配置后通话的最后一行

    然后使用FileName属性访问选定的文件名

    最后把它传给任何你需要传给ie的人

    private void btnSave_Click(object sender, EventArgs e)
    {
        SaveFileDialog save = new SaveFileDialog();
        save.InitialDirectory = @"C:\";
        save.RestoreDirectory = true;
        save.Title = "Select save location file name";
        save.DefaultExt = "xml"; // surely should be xlsx??
    
        //Showing the dialog
        if(save.ShowDialog() == DialogResult.OK)
        {
            ToExcel(save.FileName);
        }
    }
    private void ToExcel(string saveFile){...}
    

    此外,如果您想获取文件信息的方向,请检查 FileInfo.Directory