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

推荐订阅源

T
Threatpost
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security Affairs
N
News and Events Feed by Topic
T
Tenable Blog
P
Proofpoint News Feed
W
WeLiveSecurity
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
Help Net Security
Help Net Security
I
Intezer
T
Threat Research - Cisco Blogs
S
Secure Thoughts
C
Cyber Attacks, Cyber Crime and Cyber Security
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
Google Online Security Blog
Google Online Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
The Hacker News
The Hacker News
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tor Project blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
A
Arctic Wolf
Forbes - Security
Forbes - Security
O
OpenAI News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Latest
Security Latest
P
Palo Alto Networks Blog
S
Schneier on Security
S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
H
Heimdal Security Blog
V
Vulnerabilities – Threatpost
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园_首页
T
Troy Hunt's Blog
Latest news
Latest news
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
L
LINUX DO - 热门话题
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
V
Visual Studio Blog
H
Hacker News: Front Page

博客园 - 落叶潇潇雨

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;
            }
        }
    }