需要在用户桌面上创建excel表格

本文关键字:创建 excel 表格 桌面 用户 | 更新日期: 2023-09-27 17:59:06

在我的项目中,我需要在用户桌面上创建一个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:''Visual Studio 2015''Projects''AMCalculator''AMCalculator''bin''Debug文件夹中复制exe并保存在另一台机器中时,它显示错误,任何人都可以帮助这个

需要在用户桌面上创建excel表格

我在类中添加了try/catch块在ExcelUtils类:

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);
            }
            }