0

Excel スプレッドシートを生成し、指定した場所に保存するこのコードを作成しました。次に、保存された場所からファイルを読み取り、ユーザーに保存場所を尋ねて、「名前を付けて保存」ダイアログボックスを表示したいと思います。

Excel.Application excelApp = null;
            Excel.Workbook wb = null;
            Excel.Worksheet ws = null;
            Excel.Range range = null;

excelApp = new Excel.Application();
            wb = excelApp.Workbooks.Add();
            ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;

for(int i = 0; i< 10;++i) {
    ws.Cells[i, 1] = i+
}

wb.SaveAs(@"C:\test.xls", Excel.XlFileFormat.xlWorkbookNormal);
wb.Close(true);
excelApp.Quit();

次の形式でダウンロードするにはどうすればよいですか?

string str = "Hello, world"; 

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); 

return File(bytes, "text/plain"); 
4

1 に答える 1

0

これがc:\temp\excelDoc.xlsに保存された Excel ドキュメントであり、このようなリンクを持つWeb フォームがあるとします。

<asp:LinkButton runat="server" ID="GetExcel" OnClick="GetExcel_Click">Download</asp:LinkButton>

コードビハインドでは、ディスクからファイルを読み取り、次のような方法でユーザーに送信できます

    protected void GetExcel_Click(object sender, EventArgs e)
    {
        var fileName = "excelDoc.xls";
        using (var cs = new FileStream(@"c:\temp\" + fileName, FileMode.Open))
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/vnd.ms-excel";


            byte[] buffer = new byte[32768];
            int read;
            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                Response.OutputStream.Write(buffer, 0, read);
            }

            Response.End();
            Response.Flush();
        }
    }
于 2013-03-07T14:58:17.167 に答える