如何设置Excel.WorkBook.SaveAs()的目录?

时间:2013-09-04 21:52:39

标签: c# excel-interop

我有将.CSV文件转换为.XLSX文件的代码。转换顺利,但WorkBook.SaveAs(@“file.xslx”)方法似乎只将文件保存到C:\ Users [MyName] \ Documents \ file.xlsx。当我使用Excel.Application.GetSaveAsFileName()时,默认为C:\ Users [MyName] \ Documents,并带有“另存为”对话框。

此外,设置Excel.Application.DefaultFilePath似乎没有帮助,除非我明确说明F:.........

我有一个相对工作目录集,其中读取了a.csv:

 using Excel = Microsoft.Office.Interop.Excel;


        StreamReader a = new StreamReader(@"a.csv");
        var CSVContent = new List<string[]>();
        Excel.Application excel = new Excel.Application();
        excel.DefaultFilePath = @"Output\";   //doesn't do anything
        Excel.Workbook workBook = excel.Workbooks.Add();
        Excel.Worksheet sheet = workBook.ActiveSheet;

        while (!a.EndOfStream)
        {
            string read = a.ReadLine();
            CSVContent.Add(read.Split(','));
        }

        for (int i = 0; i < CSVContent.Count; i++)  //write List contents to xlsx Line by Line
        {
            string[] csvLine = CSVContent[i];
            for (int j = 0; j < csvLine.Length; j++)
            {
                sheet.Cells[i + 1, j + 1] = csvLine[j]; //Cells begin at 1 in Excel
            }
        }

        var b = excel.GetSaveAsFilename("a.xlsx");

        workBook.SaveAs(b);
        workBook.Close();

如何将workbook.SaveAs()保存到解决方案的相对工作目录中?

1 个答案:

答案 0 :(得分:1)

依赖相对路径往往会有问题。如果要将其保存到应用程序的当前目录,请使用Environment.CurrentDirectory,即:

var b = Environment.CurrentDirectory + @"\a.xlsx";