zoukankan      html  css  js  c++  java
  • C#Excel导出导入

    using System;
    using System.Collections.Generic;
    using NPOI;
    using NPOI.HPSF;
    using NPOI.HSSF;
    using NPOI.HSSF.UserModel;
    using NPOI.POIFS;
    using NPOI.Util;
    using System.Text;
    using System.IO;
    using System.Data;
    using System.Data.OleDb;
    using NPOI.SS.UserModel;
    
    namespace Business
    {
        public class CExcelOut
        {
            /// <summary>导出EXCEL表</summary>
            /// <param name="table">table表</param>
            /// <returns>二进制流</returns>
            public MemoryStream GetExecOut(DataTable table)
            {
                if (table == null)
                {
                    return null;
                }
                List<DataTable> listTable = new List<DataTable>();
                listTable.Add(table);
                return GetExecOut(listTable);
            }
            /// <summary>导入多个EXCEL表</summary>
            /// <param name="listTable">表集合</param>
            /// <returns>二进制流</returns>
            public MemoryStream GetExecOut(List<DataTable> listTable)
            {
                try
                {
                    if (listTable == null || listTable.Count == 0)
                    {
                        return null;
                    }
                    Dictionary<string, DataTable> rowTable = new Dictionary<string, DataTable>();
                    for (int i = 0; i < listTable.Count; i++)
                    {
                        rowTable.Add("sheet" + (i + 1), listTable[i]);
                    }
                    return GetExecOut(rowTable);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
            }
            /// <summary>导入多个EXCEL表 键是表名 值是table表</summary>
            /// <param name="listTable">键值对集合</param>
            /// <returns>二进制流</returns>
            public MemoryStream GetExecOut(Dictionary<string, DataTable> listTable)
            {
                if (listTable == null || listTable.Count == 0)
                {
                    return null;
                }
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                try
                {
                    foreach (KeyValuePair<string, DataTable> item in listTable)
                    {
                        string steerName = item.Key;
                        //文件名
                        NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(steerName);
                        //头部
                        NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
                        foreach (DataColumn itemColumn in item.Value.Columns)
                        {
                            headerRow.CreateCell(itemColumn.Ordinal).SetCellValue(itemColumn.ColumnName);
                        }
                        int rowIndex = 1;
                        foreach (DataRow itemRow in item.Value.Rows)
                        {
                            NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                            foreach (DataColumn itemColumn in item.Value.Columns)
                            {
                                dataRow.CreateCell(itemColumn.Ordinal).
                                    SetCellValue(itemRow[itemColumn.ColumnName].ToString());
                            }
                            rowIndex++;
                        }
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    return ms;
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
                finally
                {
                    workbook = null;
                }
            }
            /// <summary>把流转换为文件</summary>
            /// <param name="PathUrl">文件路径,如果文件存在则覆盖,不存在创建</param>
            /// <param name="ms">IO流</param>
            public void ExeclOut(string PathUrl, Stream ms)
            {
                try
                {
                    if (PathUrl.Length == 0 || ms == null)
                    {
                        return;
                    }
                    FileStream file = new FileStream(PathUrl, FileMode.Create);
                    if (ms.CanRead)
                    {
                        int lentgth = 4096;
                        byte[] by = new byte[lentgth];
                        lentgth = ms.Read(by, 0, lentgth);
                        while (lentgth != 0)
                        {
                            file.Write(by, 0, lentgth);
                            lentgth = ms.Read(by, 0, lentgth);
                        }
                        file.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
    
            /// <summary>Excel表变成dataTable</summary>
            /// <param name="filePath">Excel表格路径</param>
            /// <param name="sheetName">查询表名</param>
            /// <returns>数据集合</returns>
            public DataTable GetTop1ExcelData(string filePath, string sheetName)
            {
                DataSet ds = new DataSet();
                try
                {
    
                    string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended properties=Excel 8.0;";
                    string sql = "select * from [" + sheetName + "$]";
                    using (OleDbConnection con = new OleDbConnection(connectionString))
                    {
                        OleDbCommand cmd = new OleDbCommand(sql, con);
                        OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
                        adapt.Fill(ds);
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            return ds.Tables[0];
                        }
                        return null;
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                    return null;
                }
            }
    
            /// <summary>Excel表变成dataTable</summary>
            /// <param name="filePath">Excel表格路径</param>
            /// <param name="sheetName">查询表名</param>
            /// <returns>数据集合</returns>
            public DataTable GetExcelData(string filePath, string sheetName)
            {
                DataSet ds = new DataSet();
                try
                {
                    string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended properties='Excel 8.0;HDR=NO;IMEX=1'";
                    string sql = "select * from [" + sheetName + "$]";
                    using (OleDbConnection con = new OleDbConnection(connectionString))
                    {
                        OleDbCommand cmd = new OleDbCommand(sql, con);
                        OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
                        adapt.Fill(ds);
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            return ds.Tables[0];
                        }
                        return null;
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                    return null;
                }
            }
            /// <summary>
            /// Excel表变成dataTable
            /// </summary>
            /// <param name="filePath">Excel表格路径</param>
            /// <returns>数据集合</returns>
            public DataTable GetExcelData(string filePath)
            {
                DataTable table = new DataTable();
                try
                {
                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileStream);
    
                    ISheet iSheet = hssfWorkbook.GetSheetAt(0);
                    if (iSheet != null)
                    {
                        IRow iRow = iSheet.GetRow(0);
                        int cellCount = iRow.LastCellNum;
    
                        for (int i = iRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(iRow.GetCell(i).StringCellValue);
                            table.Columns.Add(column);
                        }
    
                        int rowCount = iSheet.LastRowNum;
                        for (int i = (iSheet.FirstRowNum + 1); i < iSheet.LastRowNum; i++)
                        {
                            IRow row = iSheet.GetRow(i);
                            DataRow dataRow = table.NewRow();
    
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    dataRow[j] = row.GetCell(j).ToString();
                                }
                            }
    
                            table.Rows.Add(dataRow);
                        }
                    }
    
                    fileStream.Flush();
                    fileStream.Dispose();
                    fileStream.Close();
                    fileStream = null;
    
                    hssfWorkbook.Dispose();
                    hssfWorkbook = null;
                    iSheet.Dispose();
                    iSheet = null;
                }
                catch (Exception exp)
                {
    
                }
                finally
                {
                }
                return table;
            }
            /// <summary>
            /// App设置导出Excel模板
            /// </summary>
            /// <param name="tbData"></param>
            /// <param name="headTb"></param>
            /// <param name="steerName"></param>
            /// <returns></returns>
            public MemoryStream GetExecOut(DataTable tbData, DataTable headTb, string steerName)
            {
                if (tbData == null || tbData.Rows.Count == 0)
                {
                    return null;
                }
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                try
                {
                    //文件名
                    NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(steerName);
                    ICellStyle style = GetStyle(workbook);
                    ICellStyle styleLeft = GetStyle(workbook, HorizontalAlignment.LEFT);
                    ICellStyle styleSize = GetStyle(workbook, 11);
    
                    int rowIndex = 0;
                    //头部
                    NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(rowIndex);
                    ICell cell = headerRow.CreateCell(0, CellType.STRING);
                    cell.SetCellValue("分层标电子水准测量记录手簿");
                    cell.CellStyle = style;
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, 0, 7));
                    //设置单元格的高度实际是设置其所在行高,所以要在单元格所在行上设置行高,行高设置数值好像是像素点的1/20,所以*20以便达到设置效果;
                    //设置单元格的宽度实际上是设置其所在列宽,所以要在单元格所在列上设置(列的设置在工作表上),宽度数值好像是字符的1/256,所以*256以便达到设置效果。
                    for (int i = 0; i < 8; i++)
                    {
                        sheet.SetColumnWidth(i, 30 * 140);
                    }
                    headerRow.Height = 20 * 21;
                    rowIndex++;
                    foreach (DataRow itemRow in headTb.Rows)
                    {
                        headerRow = sheet.CreateRow(rowIndex);
                        cell = headerRow.CreateCell(0, CellType.STRING);
                        cell.SetCellValue(itemRow["Columns1"].ToString());
                        cell.CellStyle = style;
    
                        cell = headerRow.CreateCell(1, CellType.STRING);
                        cell.SetCellValue(itemRow["Columns2"].ToString());
                        cell.CellStyle = styleLeft;
    
                        cell = headerRow.CreateCell(2, CellType.STRING);
                        cell.CellStyle = style;
    
                        cell = headerRow.CreateCell(3, CellType.STRING);
                        cell.CellStyle = style;
    
                        cell = headerRow.CreateCell(4, CellType.STRING);
                        cell.SetCellValue(itemRow["Columns3"].ToString());
                        cell.CellStyle = style;
    
                        cell = headerRow.CreateCell(5, CellType.STRING);
                        cell.SetCellValue(itemRow["Columns4"].ToString());
                        cell.CellStyle = styleLeft;
    
                        cell = headerRow.CreateCell(6, CellType.STRING);
                        cell.CellStyle = style;
    
                        cell = headerRow.CreateCell(7, CellType.STRING);
                        cell.CellStyle = style;
    
                        headerRow.Height = 20 * 21;
                        //跨行 跨列 起始行 终止行 起始列 终止列
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, 1, 3));
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, 5, 7));
                        rowIndex++;
                    }
                    NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                    dataRow.Height = 20 * 22;
                    sheet.SetColumnWidth(rowIndex, 30 * 140);
                    cell = dataRow.CreateCell(0, CellType.STRING);
                    cell.SetCellValue("测回编号");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(1, CellType.STRING);
                    cell.SetCellValue("标点编号");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(2, CellType.STRING);
                    cell.SetCellValue("中丝读数1");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(3, CellType.STRING);
                    cell.SetCellValue("中丝读数2");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(4, CellType.STRING);
                    cell.SetCellValue("中丝读数3");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(5, CellType.STRING);
                    cell.SetCellValue("距离");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(6, CellType.STRING);
                    cell.SetCellValue("中丝读数均值");
                    cell.CellStyle = styleSize;
    
                    cell = dataRow.CreateCell(7, CellType.STRING);
                    cell.SetCellValue("高差");
                    cell.CellStyle = styleSize;
    
                    rowIndex++;
                    foreach (DataRow itemRow in tbData.Rows)
                    {
                        dataRow = sheet.CreateRow(rowIndex);
                        dataRow.Height = 20 * 22;
                        foreach (DataColumn itemColumn in tbData.Columns)
                        {
                            dataRow.CreateCell(itemColumn.Ordinal, CellType.STRING).SetCellValue(itemRow[itemColumn.ColumnName].ToString());
                            dataRow.Cells[itemColumn.Ordinal].CellStyle = styleSize;
                        }
                        rowIndex++;
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    return ms;
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
                finally
                {
                    workbook = null;
                }
            }
            /// <summary>
            /// App原始中间报表导出模板
            /// </summary>
            /// <param name="tbData"></param>
            /// <returns></returns>
            public MemoryStream GetExcelOut(DataTable tbData)
            {
                if (tbData == null || tbData.Rows.Count == 0)
                {
                    return null;
                }
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                try
                {
                    //文件名
                    NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
                    ICellStyle style = GetStyle(workbook);
                    ICellStyle styleSize = GetStyle(workbook, 11);
    
                    int rowIndex = 0;
                    //头部
                    NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(rowIndex);
                    //设置单元格的高度实际是设置其所在行高,所以要在单元格所在行上设置行高,行高设置数值好像是像素点的1/20,所以*20以便达到设置效果;
                    //设置单元格的宽度实际上是设置其所在列宽,所以要在单元格所在列上设置(列的设置在工作表上),宽度数值好像是字符的1/256,所以*256以便达到设置效果。
                    headerRow.Height = 20 * 21;
                    foreach (DataColumn itemColumn in tbData.Columns)
                    {
                        ICell cell = headerRow.CreateCell(itemColumn.Ordinal, CellType.STRING);
                        cell.SetCellValue(itemColumn.ColumnName);
                        cell.CellStyle = style;
                        //设置列宽度
                        sheet.SetColumnWidth(itemColumn.Ordinal, 30 * 160);
                    }
    
                    rowIndex++;
                    foreach (DataRow itemRow in tbData.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        dataRow.Height = 20 * 22;
                        foreach (DataColumn itemColumn in tbData.Columns)
                        {
                            dataRow.CreateCell(itemColumn.Ordinal, CellType.STRING).SetCellValue(itemRow[itemColumn.ColumnName].ToString());
                            dataRow.Cells[itemColumn.Ordinal].CellStyle = styleSize;
                        }
                        rowIndex++;
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    return ms;
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
                finally
                {
                    workbook = null;
                }
            }
            /// <summary>
            /// 获取默认样式
            /// </summary>
            /// <param name="workbook"></param>
            /// <returns></returns>
            public ICellStyle GetStyle(HSSFWorkbook workbook)
            {
                return GetStyle(workbook, 14, HorizontalAlignment.CENTER_SELECTION);
            }
            /// <summary>
            /// 获取样式
            /// </summary>
            /// <param name="workbook"></param>
            /// <param name="size">设置字体大小</param>
            /// <returns></returns>
            public ICellStyle GetStyle(HSSFWorkbook workbook, short size)
            {
                return GetStyle(workbook, size, HorizontalAlignment.CENTER_SELECTION);
            }
            /// <summary>
            /// 获取样式
            /// </summary>
            /// <param name="workbook"></param>
            /// <param name="ali">设置文本居中</param>
            /// <returns></returns>
            public ICellStyle GetStyle(HSSFWorkbook workbook, HorizontalAlignment ali)
            {
                return GetStyle(workbook, 14, ali);
            }
            /// <summary>
            /// 获取样式
            /// </summary>
            /// <param name="workbook"></param>
            /// <param name="size">设置字体大小</param>
            /// <param name="ali">设置文本居中</param>
            /// <returns></returns>
            public ICellStyle GetStyle(HSSFWorkbook workbook, short size, HorizontalAlignment ali)
            {
                try
                {
                    ICellStyle style = workbook.CreateCellStyle();
                    //居中
                    style.VerticalAlignment = VerticalAlignment.CENTER;
                    //水平居中
                    style.Alignment = ali;
                    //设置字体
                    IFont font = workbook.CreateFont();
                    font.FontName = "微软雅黑";
                    //设置大小
                    font.FontHeightInPoints = size;
                    style.SetFont(font);
                    return style;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
    
        }
    }

    NPOI.DLL下载地址 https://files.cnblogs.com/files/changeMe/NPOI.zip

  • 相关阅读:
    应用服务器安装
    datasnap的线程池
    压缩OLEVARIANT数据
    服务端日志记录
    提交主从表的多个已经修改的数据
    MySQL与PostgreSQL相比哪个更好?
    Vue入门常用指令详解
    Laravel模型事件的实现原理详解
    Git 遇到了 early EOF indexpack failed 问题
    Laravel 代码开发最佳实践
  • 原文地址:https://www.cnblogs.com/changeMe/p/4421478.html
Copyright © 2011-2022 走看看