ASP.NET MVC5下載數據到Excel文件


項目中的一個功能是將數據導入到Excel文件中,這里使用NPOI操作Excel,代碼如下:

public class Excel : IDataTransfer
{
    public Stream Export(string[] titles, List<string>[] dataSource)
    {
        return ExportData(titles, dataSource);
    }

    protected virtual Stream ExportData(string[] titles, List<string>[] dataSource)
    {
        if (dataSource == null)
        {
            throw new ArgumentNullException();
        }
        HSSFWorkbook book = new HSSFWorkbook();
        ISheet sheet = book.CreateSheet("sheet1");
        int rowCount = dataSource.Length;
        int cellCount = dataSource[0].Count;

        var titleRow = sheet.CreateRow(0);
        #region header style
            // 該行的高度
            titleRow.HeightInPoints = 18;
            // 列的樣式
            ICellStyle headStyle = book.CreateCellStyle();
            // 單元格內容居中顯示
            headStyle.Alignment = HorizontalAlignment.Center;
            // 字體樣式
            IFont font = book.CreateFont();
            // 字體大小
            font.FontHeightInPoints = 12;
            // 粗體
            font.Boldweight = 1200;
            // 字體顏色
            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
            headStyle.SetFont(font);
            // 邊框
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            headStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            #endregion

        for (int i = 0; i < titles.Length; i++)
        {
            ICell cell = titleRow.CreateCell(i);
            cell.SetCellValue(titles[i]);
            cell.CellStyle = headStyle;
        }

        for (int i = 0; i < rowCount; i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            for (int j = 0; j < cellCount; j++)
            {
                row.CreateCell(j).SetCellValue(dataSource[i][j]);
            }
        }

        Stream stream = new MemoryStream();
        book.Write(stream);
        book.Close();
        stream.Position = 0;
        return stream;
    }
}

Contorller中的代碼:

Excel excel = new Excel();
Stream dataStream = excel.Export(titles.ToArray(), data);
return new FileStreamResult(dataStream, "application/ms-excel") { FileDownloadName = "exportInfo.xlsx" };

 

整個功能的實現並沒有太大難度,這里有一點需要注意就是Excel類中的protected virtual Stream ExportData(string[] titles, List<string>[] dataSource)方法,這個方法返回一個流,流中包含要導出的數據。方法的倒數第二行:stream.Position = 0;,這里需要特別注意,將數據寫入流中之后,流的位置在最末端,我們要將流的位置重置到起始位置,否則無法讀取流中的數據,也就無法導出流中的數據了。

參考文章:

asp.net MVC4.0 將數據 導出 excel 表格
MemoryStream類

版權聲明

本文為作者原創,版權歸作者雪飛鴻所有。 轉載必須保留文章的完整性,且在頁面明顯位置處標明原文鏈接

如有問題, 請發送郵件和作者聯系。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM