我想知道是否有一种方法可以使用 C# 在 excel 电子表格中找到绘制的箭头。例如,如果有一个从 A2 到 A6 的箭头,C# 程序可以打开那个 excel 文件,搜索箭头,然后返回单元格 A2 和 A6,或者类似的东西。抱歉,这听起来像是一个愚蠢的问题,但这是一个“管理问题”,我似乎找不到答案。谢谢大家。
问问题
1513 次
1 回答
7
当您在 Excel 中谈论箭头形状时,有 28 种类型的箭头形状。见下图
整个列表可以从这里检索
因此,当您循环遍历形状时,您必须考虑所有这些。理查德摩根在评论中提到的也是正确的。您必须使用TopLeftCell.Address
andBottomRightCell.Address
来查找范围。
你的代码看起来像这样。(顺便说一句,我正在使用 Interop 来自动化 Excel)
假设我们的工作表看起来像这样。现在我们不想要红色形状,因为它们不是箭头形状。
我的假设
有一个工作簿被调用Shapes.xlsx
,C:\
我们必须从中检索信息
代码(在 VS 2010 和 Excel 2010 中经过试验和测试)
using System;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
// Open a File
xlWorkBook = xlexcel.Workbooks.Open("C:\\Shapes.xlsx", 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
foreach (Microsoft.Office.Interop.Excel.Shape Shp in xlWorkSheet.Shapes)
{
// Disclaimer: I am a vb.net guy so if you feel the syntax of switch should be written
// in some other way then feel free to edit it :) In VB.Net, I could write
// Case 33 To 60 instead of writing so many cases.
switch ((int)Shp.AutoShapeType)
{
case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48:
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56:
case 57: case 58: case 59: case 60:
MessageBox.Show("Shape Found in Cell Range from " +
Shp.TopLeftCell.Address +
" to " +
Shp.BottomRightCell.Address);
break;
}
}
//Once done close and quit Excel
xlWorkBook.Close(false, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
这些是我得到的 3 个消息框
于 2013-09-13T18:16:53.373 回答