2016-07-27 135 views
0

在我的项目中,我需要在用户桌面上创建一个excel文件。代码写在我的视觉工作室是。需要在用户桌面上创建excel表格

string sPathTestData1 = "\\AdaptiveModulations.xls"; 
        string sPathTestData = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations" + sPathTestData1; 
        string sheet = "Sheet1"; 
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations"; 
    if (!Directory.Exists(path)) 
       { 
        Directory.CreateDirectory(path); 
        ExcelUtils.createExcelFile(sPathTestData,sheet); 
       } 
       else 
       { 
        ExcelUtils.setExcelFile(sPathTestData,sheet); 


       } 

此代码是在我的系统可以正常使用,并用Excel生成文件夹,但是当我复制从C EXE:\的Visual Studio 2015年\项目\ AMCalculator \ AMCalculator \ BIN \ Debug文件夹,并保存在另一台机器其示值误差任何人都可以在这个

+3

“它显示错误”aaaaaa和可能是什么错误?哪一行是发生错误? – itsme86

+0

你会得到什么错误? – Alex

+0

当我在Visual Studio中运行应用程序时,我没有得到任何错误和应用程序正常工作,也创建文件夹和Excel文件。但如果我在其他系统或外部Visual Studio中运行.exe文件,应用程序正在创建文件夹而不是Excel文件,并且应用程序停止工作,这是我的错误。 – Srikanth

回答

0

我已经在我的课 在ExcelUtils类添加try/catch块帮助:

public static void createExcelFile(String filepath, String sheetName) 
     { 
      try 
      { 
       using (FileStream stream = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite)) 
       { 
         workBook = new HSSFWorkbook(); 
         workSheet = workBook.CreateSheet(sheetName); 
         workBook.Write(stream); 
         stream.Close(); 
       } 
      } 
      catch (Exception e) { 
       Console.WriteLine("Unable to Create File. Exception is : " + e); 
      } 
     } 

     public static void setExcelFile(string filepath, string sheetName) 
     { 
      try 
      { 
       Console.WriteLine("File Path is : " + filepath); 
       workBook = WorkbookFactory.Create(new FileStream(
           Path.GetFullPath(filepath), 
           FileMode.Open, FileAccess.Read, 
           FileShare.ReadWrite)); 

       workSheet = workBook.GetSheet(sheetName); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Unable to Load File. Exception is : " + e); 
      } 
     } 

在我的主类:

  if (!File.Exists(sPathTestData)) 
      { 
       Directory.CreateDirectory(path); 
      try 
      { 
       ExcelUtils.createExcelFile(sPathTestData, sheet); 
      } 
      catch (FileNotFoundException fe) 
      { 
       Console.WriteLine("Unable to Create File. Exception is : " + fe); 
      } 
      } 
      else 
      { 
      try 
      { 
       ExcelUtils.setExcelFile(sPathTestData, sheet); 
      } 
      catch (FileNotFoundException fe) 
      { 
       Console.WriteLine("Unable to Load File. Exception is : " + fe); 
      } 
      }