c#如何获取来自剪贴板的EXCEL复制的表格

本文介绍了一种使用C#从剪贴板读取并解析Excel数据的方法,通过将剪贴板内容转换为字符串数组,再进一步处理成二维数组,实现了对Excel数据的快速读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键代码如下

 //获取剪贴板内容
                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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值