• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#创建写入读取excel

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 public static void CreateExcelFile(string FileName, List<UUser> luu)
        {
            if (FileName.Split('.')[FileName.Split('.').Length - 1] == "xlsx")//如果是2007版以后
            {
                //create
                object Nothing = System.Reflection.Missing.Value;
                var app = new Excel.Application();
                app.Visible = false;
                Excel.Workbook workBook = app.Workbooks.Add(Nothing);
                Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Sheets[1];
                worksheet.Name = "Sheet1";
                //headline
                int i = 1;
                foreach (UUser uu in luu)
                {

                    worksheet.Cells[1, i] = uu.name;
                    i++;
                }


                worksheet.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
                workBook.Close(false, Type.Missing, Type.Missing);
                app.Quit();
            }
            else
            {
                HSSFWorkbook wk = new HSSFWorkbook();            //创建一个名称为mySheet的表
                ISheet tb = wk.CreateSheet("Sheet1");
                //创建一行,此行为第二行
                IRow row = tb.CreateRow(1);
                for (int i = 0; i < luu.Count; i++)
                {
                    ICell cell = row.CreateCell(i);  //在第二行中创建单元格
                    cell.SetCellValue(luu[i].name);//循环往第二行的单元格中添加数据            }       
                    using (FileStream fs = File.OpenWrite(FileName))
                    {
                        wk.Write(fs);   //向打开的这个xls文件中写入mySheet表并保存。

                    }
                }





            }
        }

using Excel = Microsoft.Office.Interop.Excel;

using NExcel;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

需要这些引用 dll网上都可以下载

  /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ExcelToDataTable(string name, string sheetName, bool isFirstRowColumn)//name 是excel的地址
        {
            List<string> ls = new List<string>();
            string sss = null;
            IWorkbook workbook = null;
            string fileName = name;
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                FileStream 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.GetSheetAt(0);
                    sheet = workbook.GetSheet(sheetName);
                   
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.Cells.Count; //一行最后一个cell的编号 即总的列数
                    


                    if (isFirstRowColumn)
                    {
                       for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                           
                            
                            DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue.Replace("\n", "").Replace(" ","").Replace("\t","").Replace("\r",""));
                            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
                            {
                          
                                switch (row.GetCell(j).CellType)
                                {
                                    case NPOI.SS.UserModel.CellType.Blank: //空数据类型处理
                                        dataRow[j] = "";
                                        break;
                                    case NPOI.SS.UserModel.CellType.String: //字符串类型
                                        dataRow[j] = "'" + row.GetCell(j).StringCellValue;
                                        break;
                                    case NPOI.SS.UserModel.CellType.Numeric: //数字类型                                   
                                        if (HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))
                                        {
                                            dataRow[j] ="'"+row.GetCell(j).DateCellValue.ToShortDateString().Split(' ')[0];
                                        }
                                        else
                                        {
                                            if (row.GetCell(j).NumericCellValue.ToString().IndexOf(".") < 0)
                                                dataRow[j] = row.GetCell(j).NumericCellValue;
                                            else
                                            {
                                                dataRow[j] =Convert.ToDouble( getstr( row.GetCell(j).NumericCellValue.ToString()));
                                            
                                            }
                                        }
                                        break;
                                    case NPOI.SS.UserModel.CellType.Formula:
                                        if (fileName.IndexOf(".xlsx") < 0)
                                        {
                                            HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
                                            dataRow[j] = e.Evaluate(row.GetCell(j)).StringValue;
                                        }
                                        else
                                        {
                                            XSSFFormulaEvaluator e = new XSSFFormulaEvaluator(workbook);
                                            dataRow[j] = e.Evaluate(row.GetCell(j)).StringValue;
                                        }
                                          
                                           break;
                                    default:
                                        row.GetCell(j).SetCellType(NPOI.SS.UserModel.CellType.String);
                                        dataRow[j] = row.GetCell(j).StringCellValue;
                                        break;
                                }
                            }
                        }
                        data.Rows.Add(dataRow);
                    }
                }
                fs.Close();
                return data;
            }
            catch (Exception ex)
            {
               
               // MessageBox.Show("err:"+ex.Message);
                return new DataTable();
            }
        }


public static void DataTableToExcel(DataTable dt, Excel.Worksheet excelSheet,ProgressBar s,List<UUser> luu) { s.Maximum = dt.Rows.Count * luu.Count; s.Value = 0; s.Visible = true; int rowCount = dt.Rows.Count ; int colCount =luu.Count; object[,] dataArray = new object[rowCount+1, colCount]; for (int k = 0; k < luu.Count; k++) { string str= luu[k].name; dataArray[0, k] = str; } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < luu.Count; j++) { dataArray[i + 1, j] =dt.Rows[i][luu[j].source]; Application.DoEvents(); s.Value = s.Value + 1; } } excelSheet.Range["A1", excelSheet.Cells[rowCount+1, colCount]].Value2 = dataArray; s.Visible = false; s.Value = 0; }

这个uuser 有两个字段 Name 和 Source 

 name 是写入到新excel的列名

source 是datatable里的列名 

这个是一个excel转换的流程

如果只是读取和写入直接去掉list<uuser>即可

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
asp.net(c#)缓存Cache对象发布时间:2022-07-13
下一篇:
c#事件实例一发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap