網抓並將數據寫入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軟件,也不錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章