如何将文本插入Excel文件

时间:2015-11-09 15:07:44

标签: c# excel text coordinates worksheet

目的是使用C#将一个图像和附带的文本插入带有图片坐标的Excel文件中。插入图像没问题,但对于任何文本我都不能这样做。

例如:图像的坐标:top = 14f,left = 16f

我的插入图片的代码:

Excel.Shape img = worksheet.Shapes(,,top,left,width,height);

我的插入文字的代码:

worksheet.Cells[x,y] = "jdshfg";

这是Excel中使用行和列的一个单元格的文本插入功能。

我想从这个单元格的顶部,左边(图像的坐标)得到[x,y]。

1 个答案:

答案 0 :(得分:0)

如果我理解您的要求,则需要从Excel样式的行/列坐标转换为像素坐标。我在插入图表时遇到了同样的问题。下面的第一个功能将为您提供' x',第二个功能将为您提供' y'。

public double CellRangeToPixelWidth(Worksheet sheet, int left, int right) {
  Range range = sheet.get_Range(CellString(left - 1, 1, right - 1, 1), Type.Missing);
  return range.Width;
}

public double CellRangeToPixelHeight(Worksheet sheet, int top, int bottom) {
  Range range = sheet.get_Range(CellString(0, top, 0, bottom), Type.Missing);
  return range.Height;
}

public string CellString(int left, int top, int right, int bottom) {
  return string.Format("{0}{1}:{2}{3}", CellString(left), top, CellString(right), bottom);
}

public string CellString(int col) {
  if (col < 26)
    return ((char)('A' + col)).ToString();
  else if (col < 27 * 26)
    return ((char)('A' + col / 26 - 1)).ToString() + ((char)('A' + col % 26)).ToString();
  return "";
}
相关问题