在Open Xml中Excel单元格的位置时在CellReference中确定的其格式为[字母][数字]。其总字母标示列的位置,数字表示行的位置。在实际操作过程中我们最初取得的都是数字的行列号。所以必须知道如何在数字的行列号与CellReference格式的行列号之间是如何转化的。这个例子通过正则表达式来完成这个转化。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace ExcelAddress
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex("([A-Z]{1,3})(\\d+)");
if (regex.IsMatch(textBox1.Text))
{
ShowPosition();
}
else
{
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
}
}
private void ShowPosition()
{
Regex reg1 = new Regex("([A-Z]{1,3})(\\d+)");
MatchCollection mc = reg1.Matches(textBox1.Text);
Match m = mc[0];
string CX = m.Groups[1].Value;
string CY = m.Groups[2].Value;
char[] buffer = CX.ToCharArray();
int x = 0;
for (int i = 0; i < buffer.Length; i++)
{
int t = (int)buffer[i];
t -= 64;
for (int j = 0; j < buffer.Length -1 - i; j++)
{
t *= 26;
}
x += t;
}
int y = int.Parse(CY);
textBox2.Text = x.ToString();
textBox3.Text = y.ToString();
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
GenerateLabel();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
GenerateLabel();
}
private void GenerateLabel()
{
Regex nr = new Regex("\\d+");
if (textBox4.Text.Length > 0 && textBox5.Text.Length > 0 &&
nr.IsMatch(textBox4.Text) && nr.IsMatch(textBox5.Text))
{
int x, y,a;
x = int.Parse(textBox5.Text);
y = int.Parse(textBox4.Text);
a = 64;
StringBuilder sb = new StringBuilder();
while (x > 0)
{
int d = x % 26;
char c = d == 0 ? 'Z' : (char)(a + d);
x = (int)x / 26;
if (d == 0)
x--;
sb.Insert(0, c);
}
textBox6.Text = sb.ToString() + y.ToString();
}
else
{
textBox6.Text = string.Empty;
}
}
}
}
相关资源:http://download.csdn.net/detail/tx_officedev/4216200