赞
踩
ExcelPackage是EPPlus的入口类,解析一个Excel文件,生成ExcelWorkbook对象来表示一个Excel。该类实现了IDisposable接口,也就是说可以使用using进行对象释放。
10个构造函数,下面是常用的3个:
public ExcelPackage(); public ExcelPackage(FileInfo newFile); public ExcelPackage(Stream newStream);
不管构造函数中传入的参数是否有效,该类的Workbook属性都会自动创建,无须担心空指针问题。
ExcelWorkbook类表示了一个Excel文件,其Worksheets属性对应着Excel的各个Sheet。Worksheets属性会自动创建,不用担心空指针异常,但是其Count可能为0。
ExcelWorkbook的Properties属性可以对Office的一些属性进行设置,例如:
public string Author { get; set; } public string Title { get; set; } public string Comments { get; set; }
注意:在获取具体的Sheet时,索引号从1开始,例如:
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
一些常用属性:
sheet.DefaultColWidth = 10; //默认列宽 sheet.DefaultRowHeight = 30; //默认行高 sheet.TabColor = Color.Blue; //Sheet Tab的颜色 sheet.Cells.Style.WrapText = true; //单元格文字自动换行
对行列的增删操作:
public void InsertRow(int rowFrom, int rows); public void InsertColumn(int columnFrom, int columns); public void DeleteRow(int rowFrom, int rows); public void DeleteColumn(int columnFrom, int columns);
设置指定行或列的样式(宽、高、隐藏、自动换行、数字格式、锁定等):
sheet.Column(1).Width = 10; sheet.Row(1).Height = 30; sheet.Column(1).Hidden = true; sheet.Row(1).Hidden = true; sheet.Column(1).Style.WrapText = true; sheet.Column(1).Style.Numberformat.Format = "$#,###.00"; sheet.Row(1).Style.Locked = true;
自适应宽度设置:
public void AutoFit(); public void AutoFit(double MinimumWidth); public void AutoFit(double MinimumWidth, double MaximumWidth); //未传入MinimumWidth时,使用Sheet的DefaultColWidth作为最小值,此时若没有提前对DefaultColWidth进行设置就会报错 //此方法时对自动换行和合并的单元格无效
3个获取单元格范围的方法:
public ExcelRange this[string Address] { get; } //Address是指"A1:C5"这种格式 public ExcelRange this[int Row, int Col] { get; } public ExcelRange this[int FromRow, int FromCol, int ToRow, int ToCol] { get; }
重要属性:
public object Value { get; set; } //获取或设置单元格的值
复制单元格:
public void Copy(ExcelRangeBase Destination);
从二维数据集合中装载数据:
public ExcelRangeBase LoadFromCollection<T>(IEnumerable<T> Collection); public ExcelRangeBase LoadFromDataReader(IDataReader Reader, bool PrintHeaders); public ExcelRangeBase LoadFromText(FileInfo TextFile); //这里的文件是指CSV文件 //数据装载时,会与ExcelRange的行列进行对应,将值设置到其中,这些单元格没有样式和数字格式
样式包括字体、颜色、对齐、边框等。
range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(Color.Gray); //在设置Style.Fill的其他属性之前,必须设置PatternType //设置了Style.Fill.PatternType之后,必须设置Style.Fill.BackgroundColor,否则单元格背景为黑色 //注意Style.Fill.BackgroundColor是个只读属性,需要通过SetColor()方法设置颜色
range.Font.Color.SetColor(Color.Red);
range.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
range.Style.Numberformat.Format = "$#,###.00";
使用数字格式时,一定要自行检查格式的正确性,因为产生的过程中EPPlus不会检查其正确性,如果格式有错,在打开产生的Excel文件时会提示文件格式不正确。
2.7 公式
sheet.Cells[1, 3].range.Formula = "AVERAGE(A1, B1)"; sheet.Cells[1, 3].FormulaR1C1 = "AVERAGE(RC[-2], RC[-1])"; //以上两个公式表达意思相同——对于第一行,C列的值等于A列和B列的平均值
使用公式和使用数字格式有同样的注意事项,需要自行检查正确性。
建议总是记录当前Sheet有多少行和列,方便使用公式时定位单元格。
建议对公式相关代码进行注释,有助于其他程序员理解。
- /// <summary>
- /// 导入
- /// </summary>
- /// <param name="stream"></param>
- /// <returns></returns>
- public static ICollection<Student> Import(Stream stream)
- {
- ICollection<Student> students = new List<Student>();
-
- #region read excel
- using (stream)
- {
- ExcelPackage package = new ExcelPackage(stream);
-
- ExcelWorksheet sheet = package.Workbook.Worksheets[1];
-
- #region check excel format
- if (sheet == null)
- {
- return students;
- }
- if (!sheet.Cells[1, 1].Value.Equals("Name") ||
- !sheet.Cells[1, 2].Value.Equals("Age") ||
- !sheet.Cells[1, 3].Value.Equals("Gender") ||
- !sheet.Cells[1, 4].Value.Equals("English Score") ||
- !sheet.Cells[1, 5].Value.Equals("Math Score"))
- {
- return students;
- }
- #endregion
-
- #region get last row index
- int lastRow = sheet.Dimension.End.Row;
- while (sheet.Cells[lastRow, 1].Value == null)
- {
- lastRow--;
- }
- #endregion
-
- #region read datas
- for (int i = 2; i <= lastRow; i++)
- {
- students.Add(new Student
- {
- Name = sheet.Cells[i, 1].Value.ToString(),
- Age = int.Parse(sheet.Cells[i, 2].Value.ToString()),
- Gender = (Gender)Enum.Parse(typeof(Gender), sheet.Cells[i, 3].Value.ToString()),
- EnglishScore = int.Parse(sheet.Cells[i, 4].Value.ToString()),
- MathScore = int.Parse(sheet.Cells[i, 5].Value.ToString())
-
- });
- }
- }
-
- /// <summary>
- /// 导出
- /// </summary>
- /// <param name="students"></param>
- /// <returns></returns>
- public static MemoryStream Export(ICollection<Student> students)
- {
- MemoryStream stream = new MemoryStream();
- ExcelPackage package = new ExcelPackage(stream);
-
- package.Workbook.Worksheets.Add("Students");
- ExcelWorksheet sheet = package.Workbook.Worksheets[1];
-
- #region write header
- sheet.Cells[1, 1].Value = "Name";
- sheet.Cells[1, 2].Value = "Age";
- sheet.Cells[1, 3].Value = "Gender";
- sheet.Cells[1, 4].Value = "English Score";
- sheet.Cells[1, 5].Value = "Math Score";
- sheet.Cells[1, 6].Value = "Average Score";
-
- using (ExcelRange range = sheet.Cells[1, 1, 1, 6])
- {
- range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
- range.Style.Fill.BackgroundColor.SetColor(Color.Gray);
- range.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thick;
- range.Style.Border.Bottom.Color.SetColor(Color.Black);
- range.AutoFitColumns(4);
- }
- #endregion
-
- #region write content
- int pos = 2;
- foreach (Student s in students)
- {
- sheet.Cells[pos, 1].Value = s.Name;
- sheet.Cells[pos, 2].Value = s.Age;
- sheet.Cells[pos, 3].Value = s.Gender;
- sheet.Cells[pos, 4].Value = s.EnglishScore;
- sheet.Cells[pos, 5].Value = s.MathScore;
- sheet.Cells[pos, 6].FormulaR1C1 = "AVERAGE(RC[-1], RC[-2])";
-
- if (s.MathScore > 90 && s.EnglishScore > 90)
- {
- using (ExcelRange range = sheet.Cells[pos, 1, pos, 6])
- {
- range.Style.Font.Color.SetColor(Color.Blue);
- }
- }
- else if (s.MathScore < 80 && s.EnglishScore < 80)
- {
- using (ExcelRange range = sheet.Cells[pos, 1, pos, 6])
- {
- range.Style.Font.Color.SetColor(Color.Red);
- }
- }
-
- using (ExcelRange range = sheet.Cells[pos, 1, pos, 6])
- {
- range.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
- range.Style.Border.Bottom.Color.SetColor(Color.Black);
- range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
- }
- pos++;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。