关键代码如下
//获取剪贴板内容
string pasteText = Clipboard.GetText();
//判断是否有字符存在
if (string.IsNullOrEmpty(pasteText))
return;
//以换行符分割的数组
string[] lines = pasteText.Trim().Split('\n');
//以制表符分割的数组
string[] vals = lines[0].Split('\t');
class ExcelData {
/// <summary>
/// 得到来自excel中复制的数据
/// </summary>
/// <returns></returns>
public string[,] GetExcelPaste()
{
try
{
//从剪贴板获取EXCEL粘贴的数据
string pasteText = Clipboard.GetText();
//判断是否有字符存在
if (string.IsNullOrEmpty(pasteText)) return null;
//以换行符分割的数组
string[] lines = pasteText.Trim().Split('\n');
//以制表符分割的数组
string[] vals = mergesame_t(lines[0]).Split('\t');
//得到数组的行和列数
int row = lines.Length;
int col = vals.Length;
string[,] array = new string[row, col];
for (int i = 0; i < row; i++)
{
string[] vals1 = mergesame_t(lines[i]).Split('\t');
for (int j = 0; j < col; j++)
{
array[i, j] = vals1[j];
}
}
return array;
}
catch (SystemException ex)
{
return null;//excel复制的不是规则的二维数据,可能存在每行列数不一样
}
}
/// <summary>
/// 合并连续的\t
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string mergesame_t(string str)
{
bool isContinue = false;//是否是连续的\t
string result = "";
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if (ch == '\r') continue;
if (ch == '\t')
{
if (!isContinue) isContinue = true;
else continue;
}
else isContinue = false;
result += ch;
}
char tail = result[result.Length - 1];
if (tail == '\t') result = result.Substring(0, result.Length - 1);
return result;
}
}
来源:优快云 原文:https://blog.youkuaiyun.com/Metal1/article/details/71189218?utm_source=copy