向单元格写入数据,对当前WorkSheet操作

来源:互联网 发布:知乎中药学读后感 编辑:程序博客网 时间:2024/05/17 07:59

/// <summary>
  /// 向单元格写入数据,对当前WorkSheet操作
  /// </summary>
  /// <param name="rowIndex">行索引</param>
  /// <param name="columnIndex">列索引</param>
  /// <param name="text">要写入的文本值</param>
  public void SetCells(int rowIndex,int columnIndex,string text)
  {
   try
   {
    workSheet.Cells[rowIndex,columnIndex] = text;
   }
   catch
   {
    this.KillExcelProcess();
    throw new Exception("向单元格[" + rowIndex + "," + columnIndex + "]写数据出错!");
   }
  }

  /// <summary>
  /// 向单元格写入数据,对指定WorkSheet操作
  /// </summary>
  /// <param name="sheetIndex">工作表索引</param>
  /// <param name="rowIndex">行索引</param>
  /// <param name="columnIndex">列索引</param>
  /// <param name="text">要写入的文本值</param>
  public void SetCells(int sheetIndex,int rowIndex,int columnIndex,string text)
  {
   try
   {
    this.ChangeCurrentWorkSheet(sheetIndex); //改变当前工作表为指定工作表
    workSheet.Cells[rowIndex,columnIndex] = text;
   }
   catch
   {
    this.KillExcelProcess();
    throw new Exception("向单元格[" + rowIndex + "," + columnIndex + "]写数据出错!");
   }
  }

  /// <summary>
  /// 向单元格写入数据,对每个WorkSheet操作
  /// </summary>
  /// <param name="ht">Hashtable的键值对保存单元格的位置索引(行索引和列索引用“,”隔开)和数据</param>
  public void SetCells(Hashtable ht)
  {
   int rowIndex;
   int columnIndex;
   string position;

   if(ht.Count == 0) return;

   for(int i=1;i<=this.WorkSheetCount;i++)
   {
    workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);

    foreach(DictionaryEntry dic in ht)
    {
     try
     {
      position = dic.Key.ToString();
      rowIndex = Convert.ToInt32(position.Split(',')[0]);
      columnIndex = Convert.ToInt32(position.Split(',')[1]);
      
      workSheet.Cells[rowIndex,columnIndex] = dic.Value;
     }
     catch
     {
      this.KillExcelProcess();
      throw new Exception("向单元格[" + dic.Key + "]写数据出错!");
     }
    }
   }
  }

  /// <summary>
  /// 向单元格写入数据,对指定WorkSheet操作
  /// </summary>
  /// <param name="ht">Hashtable的键值对保存单元格的位置索引(行索引和列索引用“,”隔开)和数据</param>
  public void SetCells(int sheetIndex,Hashtable ht)
  {
   int rowIndex;
   int columnIndex;
   string position;

   if(sheetIndex > this.WorkSheetCount)
   {
    this.KillExcelProcess();
    throw new Exception("索引超出范围,WorkSheet索引不能大于WorkSheet数量!");
   }

   if(ht.Count == 0) return;

   workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex);

   foreach(DictionaryEntry dic in ht)
   {
    try
    {
     position = dic.Key.ToString();
     rowIndex = Convert.ToInt32(position.Split(',')[0]);
     columnIndex = Convert.ToInt32(position.Split(',')[1]);
      
     workSheet.Cells[rowIndex,columnIndex] = dic.Value;
    }
    catch
    {
     this.KillExcelProcess();
     throw new Exception("向单元格[" + dic.Key + "]写数据出错!");
    }
   }
  }

原创粉丝点击