zoukankan      html  css  js  c++  java
  • Excel的导入和导出

    参考地址:https://www.cnblogs.com/shiliang199508/p/7365312.html

    /// <summary>
            /// create 2016-11-30 by sly 
            /// 将DataTable数据导入到excel中   此方法直接返回文件给浏览器下载
            /// </summary>
            /// <param name="data">要导入的数据</param>
            /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
            /// <param name="sheetName">要导入的excel的sheet的名称</param>
            /// <param name="widthDic">要设置的宽度(key 列下标,val 宽度大小)</param>
            /// <returns></returns>
            public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten, Dictionary<int, int> widthDic = null)
            {
                int i = 0;
                int j = 0;
                int count = 0;
                ISheet sheet = null;
    
                MemoryStream file = new MemoryStream();
    
                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);
    
                        //设置所有列宽
                        for (int l = 0; l <= data.Rows.Count; l++)
                        {
                            sheet.DefaultColumnWidth = 12;
                        }
    
                        if (widthDic != null)
                        {
                            //设定自定义宽度
                            foreach (var item in widthDic)
                            {
                                sheet.SetColumnWidth(item.Key, item.Value);
                            }
                        }
                    }
                    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;
                    }
                    int outRes = -1;
    
                    for (i = 0; i < data.Rows.Count; ++i)
                    {
                        IRow row = sheet.CreateRow(count);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            if (int.TryParse(data.Rows[i][j].ToString(), out outRes))
                            {
                                row.CreateCell(j).SetCellValue(Convert.ToInt32(data.Rows[i][j].ToString()));
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(data.Rows[i][j].ToString()) && data.Rows[i][j].ToString().Length > 10)
                                {
                                    if ((data.Rows[i][j].ToString().Substring(0, 7) == "http://" || data.Rows[i][j].ToString().Substring(0, 8) == "https://"))
                                    {
                                        var TCell = row.CreateCell(j);
                                        HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.Url);//建一个HSSFHyperlink实体,指明链接类型为URL  
                                        TCell.SetCellValue(data.Rows[i][j].ToString());
                                        link.Address = data.Rows[i][j].ToString();//给HSSFHyperlink的地址赋值                                                                      
                                        TCell.Hyperlink = link;
                                    }
                                    else
                                    {
                                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                                    }
                                }
                                else
                                {
                                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                                }
                            }
                        }
                        ++count;
                    }
                    workbook.Write(file); //写入到excel
    
                    var context = System.Web.HttpContext.Current;
                    context.Response.ContentType = "application/vnd.ms-excel";
                    context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
                    context.Response.Clear();
                    context.Response.BinaryWrite(file.GetBuffer());
                    context.Response.End();
    
    
                    return count;
            //或者用下面的,打开导出的excel格式不会报错。注意,返回值改为ActionResult
           //var memory = new MemoryStream();
                //using (var stream = new FileStream(newFile, FileMode.Open))
                //{
                  //  stream.CopyTo(memory);
                //}
                //memory.Position = 0;
    
                //return File(memory, "application/vnd.ms-excel", "order.xlsx");
    } catch (Exception ex) { return -2; } }
    /// <summary>        
            /// 将excel中的数据导入到DataTable中
            /// </summary>
            /// <param name="sheetName">excel工作薄sheet的名称</param>
            /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
            /// <returns></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.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        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 == null) continue; //没有数据的行默认是null       
    
                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
    
                    return data;
                }
                catch (Exception ex)
                {                
                    return null;
                }
            }
  • 相关阅读:
    LeetCode 146
    Codeforces Round #644 (Div. 3) 题解
    AtCoder Grand Contest 044
    约数个数求解+约数求和(唯一分解定理)(遍历map的写法!)
    [蓝桥杯][2013年第四届真题]危险系数(DFS)
    Codeforces Round #674 (Div. 3)(A->D(前缀和出现次数))
    Codeforces Round #673 (Div. 2)B. Two Arrays(贪心)
    Codeforces Round #672 (Div. 2)(A->C2)(B位运算,C贪心,DP)
    质数笔记
    2020 CCPC
  • 原文地址:https://www.cnblogs.com/kingsmart/p/13522565.html
Copyright © 2011-2022 走看看