如何在使用c#在asp.net中创建excel文件时指定路径和文件名?

时间:2012-11-10 08:59:09

标签: c# asp.net excel

我可以使用以下方法创建一个excel文件:

protected void excldwnlbtn4_Click(object sender, EventArgs e)
{
    write_on_excel();
}

public void write_on_excel()
{
    Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
    try
    {

        Excel.Workbook workbook = (Excel.Workbook)excelApp.Workbooks.Add(Missing.Value);
        Excel.Worksheet worksheet;






        // Get first Worksheet
        worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

        // Setting cell values

        ((Excel.Range)worksheet.Cells[1, "A"]).Value2 = "Vendor Code";
        ((Excel.Range)worksheet.Cells[1, "B"]).Value2 = "Vendor Password";
        ((Excel.Range)worksheet.Cells[1, "C"]).Value2 = "Vendor Name";


        workbook.Save();
        workbook.Close(0, 0, 0);
    }
    catch (Exception)
    {
        lblmsg4.Text = "File not Downloaded!!";
    }
    finally
    {
        excelApp.Quit();
    }
}

通过这个我在我的c:\ documents中创建一个.xlsx文件作为book1.xlsx,但我想指定文件夹路径和文件名,我该怎么做?

1 个答案:

答案 0 :(得分:3)

使用Save As

object missing = System.Reflection.Missing.Value;

workbook.SaveAs(@"c:\documents\book1.xlsx",
            Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
            false, false, Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);