iT邦幫忙

1

請問Visual C#要如何轉成Excel檔

Winnie 2017-11-06 09:33:1710937 瀏覽

因為公司說要做一個網站,
我是以web form製作,
要將Visual C#轉成Excel檔,
以及將Excel檔轉成Visual C#,
並要能夠匯出成Excel檔及將Excel檔匯入,
我不知該從何做起,
請問該如何做比較好~

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
小碼農米爾
iT邦高手 1 級 ‧ 2017-11-06 09:51:42
最佳解答

C# 處理 Excel 的套件推薦 Epplus,不過他只支援 Excel 2007 以上版本,
如果需要同時支援 Excel 2007 和 2003 版本可以用 NPOI,
給你參考看看
https://dotblogs.com.tw/shadow/archive/2012/07/13/73385.aspx

看更多先前的回應...收起先前的回應...
Winnie iT邦新手 5 級 ‧ 2017-11-06 10:58:11 檢舉

出現錯誤,請問該如何修改?
https://ithelp.ithome.com.tw/upload/images/20171106/20107022rGois1etXh.png

您會用 Nuget 嗎?
用 Nuget 安裝 Epplus

Winnie iT邦新手 5 級 ‧ 2017-11-06 11:06:53 檢舉

要怎麼用,麻煩教一下,謝謝~

Winnie iT邦新手 5 級 ‧ 2017-11-06 17:27:55 檢舉

請問是這樣嗎~
我想要用程式寫Excel的欄位、工作表、檔名,
麻煩教一下~謝謝~
https://ithelp.ithome.com.tw/upload/images/20171106/20107022LA6SZqjVSC.jpg

先講匯出,通常會先做一個範本,範本內 欄位 工作表 都先設好,然後程式讀取範本填入資料,再輸出到前端給使用者下載,下面程式碼片段你研究看看

var templatePath = Server.MapPath("~") + @"\Templates\Student.xlsx";

using (var package = new OfficeOpenXml.ExcelPackage(new FileInfo(templatePath)))
{
    var worksheet = package.Workbook.Worksheets.First();

    var rowIndex = 2;
    var celIndex = 1;

    foreach (var student in studentList)
    {
        worksheet.Cells[rowIndex, celIndex++].Value = student.Id;
        worksheet.Cells[rowIndex, celIndex++].Value = student.Name;
        rowIndex += 1;
        celIndex = 1;
    }

    worksheet.Cells.AutoFitColumns();

    var fileStream = new MemoryStream();
    package.SaveAs(fileStream);
    fileStream.Position = 0;
    
    var output = new byte[(int)fileStream.Length];
    fileStream.Read(output, 0, output.Length);

    //將檔案輸出到瀏覽器
    context.Response.Clear();
    context.Response.AddHeader(
        "Content-Length", output.Length.ToString());
    context.Response.ContentType = "application/octet-stream";
    context.Response.AddHeader(
        "content-disposition", 
        "attachment; filename=" + fileName);
    context.Response.OutputStream.Write(output, 0, output.Length);
    context.Response.Flush();
    context.Response.End();
}

/images/emoticon/emoticon12.gif

Winnie iT邦新手 5 級 ‧ 2017-11-07 09:44:28 檢舉

請問您的程式碼應該要放在哪個地方?
因為我找不到可以收留它的位置> <
裡面好像都用HTML

跟您確認一下問題,我可能誤會您的提問了
您是要做線上版的Excel編輯功能嗎?
這裡說的Epplus,NPOI都是沒有編輯畫面的,功能是將資料庫的資料寫入到Excel讓使用者下載檔案。

然後這些程式要放在Webform的.cs檔裡面。

Winnie iT邦新手 5 級 ‧ 2017-11-07 13:04:12 檢舉

對唷~
我要編輯功能唷~

UI介面我沒有經驗~
類似的套件有用過 handsontable,不過沒有深入研究。
/images/emoticon/emoticon20.gif

Winnie iT邦新手 5 級 ‧ 2017-11-07 16:19:56 檢舉

/images/emoticon/emoticon17.gif

Winnie iT邦新手 5 級 ‧ 2017-11-07 16:19:59 檢舉

/images/emoticon/emoticon17.gif

非常抱歉,問題理解錯誤了。 /images/emoticon/emoticon70.gif

0
石頭
iT邦高手 1 級 ‧ 2017-11-06 09:52:17

可以試試 NPOI
網路上蠻多 NPOI 的中文教學
網路教學 NPOI

我要發表回答

立即登入回答