简体   繁体   English

如何将 excel 文件保存到特定位置 C#?

[英]How to save an excel file to a specific location C#?

This is a Windows Form Application using .NET framework which saves records into a MS Database.这是一个使用 .NET 框架的 Windows 表单应用程序,它将记录保存到 MS 数据库中。 Also has the option to export database as an excel file.还可以选择将数据库导出为 excel 文件。

This is my 'Create excel file' button click function:这是我的“创建 excel 文件”按钮单击 function:

private void button5_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from [dbo].[Table]";
        cmd.ExecuteNonQuery();

        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet("New_DataSet");
        ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
        da.Fill(dt);
        ds.Tables.Add(dt);
        ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls",ds);

        MessageBox.Show("Archivo excel generado correctamente.");

        con.Close();
    }

Using my published version of the app, noticed that the excel file is created in the "C:\Users\userName\AppData\Local\Apps\2.0\ZDTK7LMQ.YEZ\V0BOPT21.N23" my default.使用我发布的应用程序版本,注意到 excel 文件是在“C:\Users\userName\AppData\Local\Apps\2.0\ZDTK7LMQ.YEZ\V0BOPT21.N23”中创建的我的默认值。

Id' like to change saving location.我想更改保存位置。 Any clues?有什么线索吗?

PD: The excel library I'm using is "ExcelLibrary". PD:我使用的 excel 库是“ExcelLibrary”。

using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat; 

What if you try add \ one slash or two slashes \ \ in front of filename and see if that makes a difference: "\MyExcelFile.xls" or "\ \ MyExcelFile.xls".如果您尝试在文件名前添加 \ 一个斜杠或两个斜杠 \ 并查看是否有所不同:“\MyExcelFile.xls”或“\ \ MyExcelFile.xls”。 Also, you may want to take out the file name and construct the file name and path as a string then add string to the call like so:此外,您可能希望取出文件名并将文件名和路径构造为字符串,然后将字符串添加到调用中,如下所示:

var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "desired_dir_name"); // bin, etc
string myFileNameAndPath = path + "\\" + "MyExcelFile.xls";
ExcelLibrary.DataSetHelper.CreateWorkbook(myFileNameAndPath ,ds);

Run debugger through above to see what paths are getting set and modify location to your needs.通过上面运行调试器以查看设置了哪些路径并根据您的需要修改位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM