惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
DataBreaches.Net
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
博客园_首页
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
IT之家
IT之家
MongoDB | Blog
MongoDB | Blog
The GitHub Blog
The GitHub Blog
月光博客
月光博客
U
Unit 42
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
腾讯CDC
B
Blog RSS Feed
博客园 - Franky
爱范儿
爱范儿

博客园 - 落叶潇潇雨

Can't get WebApplicationContext object from ContextRegistry.GetContext(): Resource handler for the 'web' protocol is not defined xml序列化与反序列化 How to debug Typescript in browser log4net使用的关键点 DataContractSerializer序列化与反序列化遇到的奇怪问题 图文安装Windows Template Library - WTL Version 9.0 WCF的传输安全(读书笔记) Asp.net mvc 各个组件的分离 同程旅游网开放平台SDK开发完成 csdn回到顶端 SQL多行变一列 Timer的schedule和scheduleAtFixedRate方法的区别解析 android 主线程和子线程之间的消息传递 activity生命周期 瀑布流插件 CSS自适应宽度圆角按钮 ajaxFileUpload上传文件和表单数据 Ajax上传表单数据和文件 使用Rhino Mocks
Asp.net 导出Excel
落叶潇潇雨 · 2016-04-08 · via 博客园 - 落叶潇潇雨

//localizedHeaders 用来转换英文列到中文列
//trimUnlocalizedColumn 用来将隐藏的列,未本地化的列删除掉

public static class ResponseHelper

    {

        public static void ResponseExcel(string tempFolder,

            DataTable dt,

            Dictionary<string, LocalizedHeader> localizedHeaders,

            bool trimUnlocalizedColumn,

            string fileName,

            string sheetName)

        {

            LocalizedColumnName(dt, localizedHeaders, trimUnlocalizedColumn);

            if (!Directory.Exists(tempFolder))

            {

                Directory.CreateDirectory(tempFolder);

            }

            if (string.IsNullOrEmpty(fileName))

            {

                fileName = Guid.NewGuid() + ".xls";

            }

            var excelPath = Path.Combine(tempFolder, fileName);

            using (ExcelHelper helper = new ExcelHelper(excelPath))

            {

                helper.DataTableToExcel(dt, sheetName ?? "Sheet1", true);

            }

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);

            HttpContext.Current.Response.Charset = "UTF-8";

            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            HttpContext.Current.Response.ContentType = "application/ms-excel";

            HttpContext.Current.Response.WriteFile(excelPath);

            HttpContext.Current.Response.End();

        }

        private static void LocalizedColumnName(DataTable dt, Dictionary<string, LocalizedHeader> localizedHeaders, bool trimUnlocalizedColumn)

        {

            if (localizedHeaders == null || localizedHeaders.Count == 0)

            {

                return;

            }

            var unlocalizedColumns = new List<string>();

            foreach (DataColumn column in dt.Columns)

            {

                if (localizedHeaders.ContainsKey(column.ColumnName))

                {

                    column.ColumnName = localizedHeaders[column.ColumnName].LocalizedName;

                }

                else

                {

                    unlocalizedColumns.Add(column.ColumnName);

                }

            }

            if (trimUnlocalizedColumn)

            {

                foreach (var unlocalizedColumn in unlocalizedColumns)

                {

                    dt.Columns.Remove(dt.Columns[unlocalizedColumn]);

                }

            }

            foreach (var localizedHeader in localizedHeaders)

            {

                

if (dt.Columns.Contains(localizedHeader.Value.LocalizedName)

                    && localizedHeader.Value.ColumnIndex < dt.Columns.Count)

                {

                    dt.Columns[localizedHeader.Value.LocalizedName].SetOrdinal(localizedHeader.Value.ColumnIndex);

                }

            }

        }

    }

    public class LocalizedHeader

    {

        public string OrignalName { get; set; }

        public string LocalizedName { get; set; }

        public int ColumnIndex { get; set; }

    }

==================================================================================================================
== Excel帮助类,调用NPOI组件
==================================================================================================================
public class ExcelHelper : IDisposable
    {
        private readonly string _fileName; //文件名
        private IWorkbook _workbook;
        private FileStream _fs;
        private bool _disposed;

        public ExcelHelper( string fileName)
        {
            _fileName = fileName;
            _disposed = false;
        }

        /// <summary>
        
/// 将DataTable数据导入到excel中
        
/// </summary>
        
/// <param name=" data"> 要导入的数据 </param>
        
/// <param name=" isColumnWritten">DataTable的列名是否要导入 </param>
        
/// <param name=" sheetName"> 要导入的excel的sheet的名称 </param>
        
/// <returns> 导入数据行数(包含列名那一行) </returns>
        public int DataTableToExcel( DataTable data, string sheetName, bool isColumnWritten)
        {
            int i;
            int j;
            int count;
            ISheet sheet;

            _fs = new FileStream(_fileName, FileMode .OpenOrCreate, FileAccess.ReadWrite);
            if (_fileName.IndexOf( ".xlsx") > 0// 2007版本
                _workbook = new XSSFWorkbook();
            else if (_fileName.IndexOf( ".xls") > 0// 2003版本
                _workbook = new HSSFWorkbook();

            try
            {
                if (_workbook != null)
                {
                    sheet = _workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true//写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                _workbook.Write(_fs); //写入到excel
                return count;
            }
            catch ( Exception ex)
            {
                Console.WriteLine( "Exception: " + ex.Message);
                return -1;
            }
        }

        /// <summary>
        
/// 将excel中的数据导入到DataTable中
        
/// </summary>
        
/// <param name=" sheetName"> excel工作薄sheet的名称 </param>
        
/// <param name=" isFirstRowColumn">第一行是否是DataTable的列名 </param>
        
/// <returns> 返回的DataTable</returns>
        public DataTable ExcelToDataTable( string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                _fs = new FileStream(_fileName, FileMode .Open, FileAccess .Read);
                if (_fileName.IndexOf( ".xlsx") > 0// 2007版本
                    _workbook = new XSSFWorkbook(_fs);
                else if (_fileName.IndexOf( ".xls") > 0// 2003版本
                    _workbook = new HSSFWorkbook(_fs);

                if (sheetName != null)
                {
                    sheet = _workbook.GetSheet(sheetName);
                    if (sheet == null//如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = _workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = _workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for ( int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.ToString();
                                DataColumn column = new DataColumn (cellValue);
                                data.Columns.Add(column);
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for ( int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == nullcontinue//没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for ( int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            ICell cell = row.GetCell(j);
                            if (cell.CellType == CellType.Numeric)
                            {
                                //NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
                                if ( DateUtil.IsCellDateFormatted(cell)) //日期类型
                                {
                                    dataRow[j] = cell.DateCellValue;
                                }
                                else//其他数字类型
                                {
                                    dataRow[j] = cell.NumericCellValue;
                                }
                            }
                            else if (cell.CellType == CellType.Blank) //空数据类型
                            {
                                dataRow[j] = "";
                            }
                            else if (cell.CellType == CellType.Formula) //公式类型
                            {
                                HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(_workbook);
                                dataRow[j] = eva.Evaluate(cell).StringValue;
                            }
                            else //其他类型都按字符串类型来处理
                            {
                                dataRow[j] = cell.StringCellValue;
                            }
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch ( Exception ex)
            {
                Console.WriteLine( "Exception: " + ex.Message);
                return null;
            }
        }

        public void Dispose()
        {
            Dispose( true);
            GC.SuppressFinalize( this);
        }

        protected virtual void Dispose( bool disposing)
        {
            if (! this._disposed)
            {
                if (disposing)
                {
                    if (_fs != null)
                        _fs.Close();
                }

                _fs = null;
                _disposed = true;
            }
        }
    }