网抓并将数据写入excel里

看到别人的提问,用C#爬了一页青塔的数据并保存到excel里。获取网页数据用了自带的webclient.处理json数据用了newtonsoft.json.将爬取的数据写入新excel表里用了npoi.

using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;

namespace 青塔
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient w = new WebClient();
            string url = "https://www.cingta.com/v1.0/api/get_subjectdetail/";
            w.Encoding = Encoding.UTF8;
            w.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            w.Headers.Add("Referer","https://www.cingta.com/data/sch");
            string postString = "name=北京大学";
            byte[] postdata = Encoding.UTF8.GetBytes(postString);
            byte[] responsedata=w.UploadData(url,postdata);
            string responsetext = Regex.Unescape( Encoding.UTF8.GetString(responsedata));
            int i=0;
            string path = @"C:\Users\FanXiaoLei\Desktop\1.xlsx";
            IWorkbook wk = new XSSFWorkbook();
            ISheet Sht = wk.CreateSheet("数据");
            
            JObject js=JObject.Parse(responsetext);
            JToken ls = js["data"]["list"];
 
            foreach(JObject items in ls)
            {
                IRow rows = Sht.CreateRow(i);
                int j = 0;
                foreach (var item in items)
                { 
                    
                    ICell cell = rows.CreateCell(j);
                     
                    cell.SetCellValue(String.Format("{0}",i==0?item.Key:item.Value));
                    
                    j++;

                }

                i++;
            }
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                wk.Write(fs);
            }
            Console.WriteLine("done!");
            Console.ReadKey();
        }
    }
}

主要查了下北大的一点数据。效果还是可以的。比起vba,数据写入单元格要啰嗦不少。不过用npoi读写不依赖excel软件,也不错。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值