ExcelHelper(Excel和C#、asp.net导入导出,通用类)(五)

http://blog.163.com/it_software/blog/static/1238582962010518113642870/


/// <summary>
  /// 插列(在指定WorkSheet指定列右边插入指定数量列)
  /// </summary>
  /// <param name="sheetIndex"></param>
  /// <param name="columnIndex"></param>
  /// <param name="count"></param>
  public void InsertColumns(int sheetIndex,int columnIndex,int count)
  {
   if(sheetIndex > this.WorkSheetCount)
   {
    this.KillExcelProcess();
    throw new Exception("索引超出范围,WorkSheet索引不能大于WorkSheet数量!");
   }

   try
   {
    workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex];
    range = (Excel.Range)workSheet.Columns[this.missing,columnIndex];

    for(int i=0;i<count;i++)
    {
     range.Insert(Excel.XlDirection.xlDown);
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 复制列(在指定列右边复制指定数量列)
  /// </summary>
  /// <param name="columnIndex"></param>
  /// <param name="count"></param>
  public void CopyColumns(int columnIndex,int count)
  {
   try
   {
    for(int n=1;n<=this.WorkSheetCount;n++)
    {
     workSheet = (Excel.Worksheet)workBook.Worksheets[n];
//     range1 = (Excel.Range)workSheet.Columns[columnIndex,this.missing];
     range1 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex)+"1",this.IntToLetter(columnIndex)+"10000");

     for(int i=1;i<=count;i++)
     {
//      range2 = (Excel.Range)workSheet.Columns[this.missing,columnIndex + i];
      range2 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex+i)+"1",this.IntToLetter(columnIndex+i)+"10000");
      range1.Copy(range2);
     }
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 复制列(在指定WorkSheet指定列右边复制指定数量列)
  /// </summary>
  /// <param name="sheetIndex"></param>
  /// <param name="columnIndex"></param>
  /// <param name="count"></param>
  public void CopyColumns(int sheetIndex,int columnIndex,int count)
  {
   if(sheetIndex > this.WorkSheetCount)
   {
    this.KillExcelProcess();
    throw new Exception("索引超出范围,WorkSheet索引不能大于WorkSheet数量!");
   }

   try
   {
    workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex];
//    range1 = (Excel.Range)workSheet.Columns[Type.Missing,columnIndex];
    range1 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex)+"1",this.IntToLetter(columnIndex)+"10000");

    for(int i=1;i<=count;i++)
    {
//     range2 = (Excel.Range)workSheet.Columns[Type.Missing,columnIndex + i];
     range2 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex+i)+"1",this.IntToLetter(columnIndex+i)+"10000");
     range1.Copy(range2);
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 删除列
  /// </summary>
  /// <param name="columnIndex"></param>
  /// <param name="count"></param>
  public void DeleteColumns(int columnIndex,int count)
  {
   try
   {
    for(int n=1;n<=this.WorkSheetCount;n++)
    {
     workSheet = (Excel.Worksheet)workBook.Worksheets[n];
     range = (Excel.Range)workSheet.Columns[this.missing,columnIndex];

     for(int i=0;i<count;i++)
     {
      range.Delete(Excel.XlDirection.xlDown);
     }
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 删除列
  /// </summary>
  /// <param name="sheetIndex"></param>
  /// <param name="columnIndex"></param>
  /// <param name="count"></param>
  public void DeleteColumns(int sheetIndex,int columnIndex,int count)
  {
   if(sheetIndex > this.WorkSheetCount)
   {
    this.KillExcelProcess();
    throw new Exception("索引超出范围,WorkSheet索引不能大于WorkSheet数量!");
   }

   try
   {
    workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex];
    range = (Excel.Range)workSheet.Columns[this.missing,columnIndex];

    for(int i=0;i<count;i++)
    {
     range.Delete(Excel.XlDirection.xlDown);
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  #endregion

  #region Range Methods

  /// <summary>
  /// 将指定范围区域拷贝到目标区域
  /// </summary>
  /// <param name="sheetIndex">WorkSheet索引</param>
  /// <param name="startCell">要拷贝区域的开始Cell位置(比如:A10)</param>
  /// <param name="endCell">要拷贝区域的结束Cell位置(比如:F20)</param>
  /// <param name="targetCell">目标区域的开始Cell位置(比如:H10)</param>
  public void RangeCopy(int sheetIndex,string startCell,string endCell,string targetCell)
  {
   if(sheetIndex > this.WorkSheetCount)
   {
    this.KillExcelProcess();
    throw new Exception("索引超出范围,WorkSheet索引不能大于WorkSheet数量!");
   }

   try
   {
    workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex);
    range1 = workSheet.get_Range(startCell,endCell);
    range2 = workSheet.get_Range(targetCell,this.missing);

    range1.Copy(range2);
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 将指定范围区域拷贝到目标区域
  /// </summary>
  /// <param name="sheetName">WorkSheet名称</param>
  /// <param name="startCell">要拷贝区域的开始Cell位置(比如:A10)</param>
  /// <param name="endCell">要拷贝区域的结束Cell位置(比如:F20)</param>
  /// <param name="targetCell">目标区域的开始Cell位置(比如:H10)</param>
  public void RangeCopy(string sheetName,string startCell,string endCell,string targetCell)
  {
   try
   {
    Excel.Worksheet sheet = null;

    for(int i=1;i<=this.WorkSheetCount;i++)
    {
     workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i);
     
     if(workSheet.Name == sheetName)
     {
      sheet = workSheet;
     }
    }

    if(sheet != null)
    {
     for(int i=sheetCount;i>=1;i--)
     {
      range1 = sheet.get_Range(startCell,endCell);
      range2 = sheet.get_Range(targetCell,this.missing);

      range1.Copy(range2);
     }
    }
    else
    {
     this.KillExcelProcess();
     throw new Exception("名称为\"" + sheetName + "\"的工作表不存在");
    }
   }
   catch(Exception e)
   {
    this.KillExcelProcess();
    throw e;
   }
  }

  /// <summary>
  /// 自动填充
  /// </summary>
  public void RangAutoFill()
  {
   Excel.Range rng = workSheet.get_Range("B4", Type.Missing);
   rng.Value2 = "星期一 ";
   rng.AutoFill(workSheet.get_Range("B4","B9"),
    Excel.XlAutoFillType.xlFillWeekdays);

   rng = workSheet.get_Range("C4", Type.Missing);
   rng.Value = "一月";
   rng.AutoFill(workSheet.get_Range("C4","C9"),
    Excel.XlAutoFillType.xlFillMonths);

   rng = workSheet.get_Range("D4",Type.Missing);
   rng.Value2 = "1";
   rng.AutoFill(workSheet.get_Range("D4","D9"),
    Excel.XlAutoFillType.xlFillSeries);

   rng = workSheet.get_Range("E4",Type.Missing);
   rng.Value2 = "3";
   rng = workSheet.get_Range("E5",Type.Missing);
   rng.Value2 = "6";
   rng = workSheet.get_Range("E4","E5");
   rng.AutoFill(workSheet.get_Range("E4","E9"),
    Excel.XlAutoFillType.xlFillSeries);

  }

  /// <summary>
  /// 应用样式
  /// </summary>
  public void ApplyStyle()
  {
   object missingValue = Type.Missing;
   Excel.Range rng = workSheet.get_Range("B3","L23");
   Excel.Style style;

   try
   {
    style = workBook.Styles["NewStyle"];
   }
    // Style doesn't exist yet.
   catch
   {
    style = workBook.Styles.Add("NewStyle", missingValue);
    style.Font.Name = "Verdana";
    style.Font.Size = 12;
    style.Font.Color = 255;
    style.Interior.Color = (200 << 16) | (200 << 8) | 200;
    style.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
   }

   rng.Value2 = "'Style Test";
   rng.Style = "NewStyle";
   rng.Columns.AutoFit();
  }

  #endregion

  #region ExcelHelper Kit
  /// <summary>
  /// 将Excel列的字母索引值转换成整数索引值
  /// </summary>
  /// <param name="letter"></param>
  /// <returns></returns>
  public int LetterToInt(string letter)
  {
   int n = 0;
   
   if(letter.Trim().Length == 0)
    throw new Exception("不接受空字符串!");

   if(letter.Length >= 2)
   {
    char c1 = letter.ToCharArray(0,2)[0];
    char c2 = letter.ToCharArray(0,2)[1];

    if(!char.IsLetter(c1) || !char.IsLetter(c2))
    {
     throw new Exception("格式不正确,必须是字母!");
    }

    c1 = char.ToUpper(c1);
    c2 = char.ToUpper(c2);

    int i = Convert.ToInt32(c1) - 64;
    int j = Convert.ToInt32(c2) - 64;

    n = i * 26 + j;
   }
   
   if(letter.Length == 1)
   {
    char c1 = letter.ToCharArray()[0];

    if(!char.IsLetter(c1))
    {
     throw new Exception("格式不正确,必须是字母!");
    }

    c1 = char.ToUpper(c1);

    n = Convert.ToInt32(c1) - 64;
   }

   if(n > 256)
    throw new Exception("索引超出范围,Excel的列索引不能超过256!");
   
   return n;
  }

  /// <summary>
  /// 将Excel列的整数索引值转换为字符索引值
  /// </summary>
  /// <param name="n"></param>
  /// <returns></returns>
  public string IntToLetter(int n)
  {
   if(n > 256)
    throw new Exception("索引超出范围,Excel的列索引不能超过256!");
    
   int i = Convert.ToInt32(n / 26);
   int j = n % 26;

   char c1 = Convert.ToChar( i + 64 );
   char c2 = Convert.ToChar( j + 64 );

   if(n > 26)
    return c1.ToString() + c2.ToString();
   else if(n == 26)
    return "Z";
   else
    return c2.ToString();
  }

  #endregion

  #region Output File(注意:如果目标文件已存在的话会出错)
  /// <summary>
  /// 输出Excel文件并退出
  /// </summary>
  public void OutputExcelFile()
  {
   if(this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

   try
   {
    workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 输出指定格式的文件(支持格式:HTML,CSV,TEXT,EXCEL)
  /// </summary>
  /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
  public void OutputFile(string format)
  {
   if(this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

   try
   {
    switch(format)
    {
     case "HTML":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "CSV":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlCSV,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "TEXT":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
//     case "XML":
//     {
//      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing,
//       Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
//       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//      break;
//
//     }
     default:
     {
      workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
    }
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 保存文件
  /// </summary>
  public void SaveFile()
  {
   try
   {
    workBook.Save();   
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 另存文件
  /// </summary>
  public void SaveAsFile()
  {
   if(this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

   try
   {
    workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 将Excel文件另存为指定格式
  /// </summary>
  /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
  public void SaveAsFile(string format)
  {
   if(this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

   try
   {
    switch(format)
    {
     case "HTML":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "CSV":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlCSV,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "TEXT":
     {
      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
//     case "XML":
//     {
//      workBook.SaveAs(outputFile,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing,
//       Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
//       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//      break;
//     }
     default:
     {
      workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
    }
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 另存文件
  /// </summary>
  /// <param name="fileName">文件名</param>
  public void SaveFile(string fileName)
  {
   try
   {
    workBook.SaveAs(fileName,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

  /// <summary>
  /// 将Excel文件另存为指定格式
  /// </summary>
  /// <param name="fileName">文件名</param>
  /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
  public void SaveAsFile(string fileName,string format)
  {
   try
   {
    switch(format)
    {
     case "HTML":
     {
      workBook.SaveAs(fileName,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "CSV":
     {
      workBook.SaveAs(fileName,Excel.XlFileFormat.xlCSV,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
     case "TEXT":
     {
      workBook.SaveAs(fileName,Excel.XlFileFormat.xlHtml,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
//     case "XML":
//     {
//      workBook.SaveAs(fileName,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing,
//       Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
//       Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//      break;
//     }
     default:
     {
      workBook.SaveAs(fileName,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);   
      break;
     }
    }
   }
   catch(Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }
  #endregion

  #endregion

  #region 私有方法

  /// <summary>
  /// 合并单元格,并赋值,对指定WorkSheet操作
  /// </summary>
  /// <param name="beginRowIndex">开始行索引</param>
  /// <param name="beginColumnIndex">开始列索引</param>
  /// <param name="endRowIndex">结束行索引</param>
  /// <param name="endColumnIndex">结束列索引</param>
  /// <param name="text">合并后Range的值</param>
  private void MergeCells(Excel.Worksheet sheet,int beginRowIndex,int beginColumnIndex,int endRowIndex,int endColumnIndex,string text)
  {
   if(sheet == null)
    return;

   range = sheet.get_Range(sheet.Cells[beginRowIndex,beginColumnIndex],sheet.Cells[endRowIndex,endColumnIndex]);
    
   range.ClearContents();  //先把Range内容清除,合并才不会出错
   range.MergeCells = true;
   range.Value = text;
   range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
   range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
  }

  /// <summary>
  /// 将指定索引列的数据相同的行合并,对指定WorkSheet操作
  /// </summary>
  /// <param name="columnIndex">要合并的列索引</param>
  /// <param name="beginRowIndex">合并开始行索引</param>
  /// <param name="rows">要合并的行数</param>
  private void MergeRows(Excel.Worksheet sheet,int columnIndex,int beginRowIndex,int rows)
  {
   int beginIndex = beginRowIndex;
   int count = 0;
   string text1;
   string text2;

   if(sheet == null)
    return;

   for(int j=beginRowIndex;j<beginRowIndex+rows;j++)
   {
    range1 = (Excel.Range)sheet.Cells[j,columnIndex];
    range2 = (Excel.Range)sheet.Cells[j+1,columnIndex];
    text1 = range1.Text.ToString();
    text2 = range2.Text.ToString();

    if(text1 == text2)
    {
     ++count;
    }
    else
    {    
     if(count > 0)
     {
      this.MergeCells(sheet,beginIndex,columnIndex,beginIndex+count,columnIndex,text1);
     }

     beginIndex = j + 1;  //设置开始合并行索引
     count = 0;  //计数器清0
    }

   }

  }


  /// <summary>
  /// 计算WorkSheet数量
  /// </summary>
  /// <param name="rowCount">记录总行数</param>
  /// <param name="rows">每WorkSheet行数</param>
  public int GetSheetCount(int rowCount,int rows)
  {
   int n = rowCount % rows;  //余数

   if(n == 0)
    return rowCount / rows;
   else
    return Convert.ToInt32(rowCount / rows) + 1;
  }
  
  /// <summary>
  /// 结束Excel进程
  /// </summary>
  public void KillExcelProcess()
  {
   Process[] myProcesses;
   DateTime startTime;
   myProcesses = Process.GetProcessesByName("Excel");

   //得不到Excel进程ID,暂时只能判断进程启动时间
   foreach(Process myProcess in myProcesses)
   {
    startTime = myProcess.StartTime;

    if(startTime > beforeTime && startTime < afterTime)
    {
     myProcess.Kill();
    }
   }
  }


  private void Dispose()
  {
   workBook.Close(null,null,null);
   app.Workbooks.Close();
   app.Quit();

   if(range != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    range = null;
   }
   if(range1 != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range1);
    range1 = null;
   }
   if(range2 != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range2);
    range2 = null;
   }
   if(textBox != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(textBox);
    textBox = null;
   }
   if(workSheet != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
    workSheet = null;
   }
   if(workBook != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
    workBook = null;
   }
   if(app != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
    app = null;
   }

   GC.Collect();

   this.KillExcelProcess();
   
  }//end Dispose
  #endregion

  
 }//end class
}//end namespace

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值