簡體   English   中英

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

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

這是一個使用 .NET 框架的 Windows 表單應用程序,它將記錄保存到 MS 數據庫中。 還可以選擇將數據庫導出為 excel 文件。

這是我的“創建 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();
    }

使用我發布的應用程序版本,注意到 excel 文件是在“C:\Users\userName\AppData\Local\Apps\2.0\ZDTK7LMQ.YEZ\V0BOPT21.N23”中創建的我的默認值。

我想更改保存位置。 有什么線索嗎?

PD:我使用的 excel 庫是“ExcelLibrary”。

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

如果您嘗試在文件名前添加 \ 一個斜杠或兩個斜杠 \ 並查看是否有所不同:“\MyExcelFile.xls”或“\ \ MyExcelFile.xls”。 此外,您可能希望取出文件名並將文件名和路徑構造為字符串,然后將字符串添加到調用中,如下所示:

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

通過上面運行調試器以查看設置了哪些路徑並根據您的需要修改位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM