Menu

Showing posts with label read. Show all posts
Showing posts with label read. Show all posts

Thursday, March 18, 2021

[NodeJS] วิธีการนำเข้าไฟล์ JSON ไปยังตัวแปรและการส่งออกค่าตัวแปรไปยังไฟล์ JSON (การอ่านและเขียนไฟล์ JSON)
[NodeJS] How to Import JSON File to Variable and Export Variable to JSON File (Reading and Writing JSON file to/from Variable)

สมมติว่า เรามีไฟล์ JSON อยู่ที่ ./resources/symbols.json และเราจะใช้ตัวแปรชื่อ symbols ในการเก็บค่าที่อ่านได้จากไฟล์ JSON  
เราสามารถอ่านไฟล์ JSON แล้วเก็บค่าเข้าตัวแปรได้ดังนี้
const symbols = require('./resources/symbols.json');
ในทางกลับกัน ถ้าเราต้องการเขียนค่าของตัวแปรออกมาเป็นไฟล์ JSON เราจะใช้วิธีดังนี้
const fs = require('fs');
const jsonData = JSON.stringify(symbols, null, 4); // third parameter defines white-space insertion for pretty-printing
fs.writeFileSync('./resources/symbols.json', jsonData);

Tuesday, September 3, 2019

[Python] วิธีการอ่านไฟล์ Excel ใน Python
[Python] How to Read Excel File in Python

การอ่านไฟล์ Excel จำเป็นต้องใช้ package xlrd ซึ่งสามารถติดตั้งโดยรันคำสั่งต่อไปนี้
pip install xlrd
ตัวอย่างการใช้งาน เช่น
import xlrd

### สั่งเปิดไฟล์ Excel
workbook = xlrd.open_workbook('filepath')

### เลือก Sheet ที่ต้องการใช้งานจากชื่อของ Sheet
worksheet = workbook.sheet_by_name('sheetname')

### เลือก Sheet ที่ต้องการใช้งานจากตำแหน่งของ Sheet
worksheet2 = workbook.sheet_by_index(0)

### แสดงจำนวนแถวทั้งหมด
print(worksheet.nrows)

### แสดงจำนวนคอลัมน์ทั้งหมด
print(worksheet.ncols)

### แสดงค่าข้อมูลแถวที่ระบุ
print(worksheet.row_values(1))

### แสดงค่าข้อมูล cell ที่ระบุ
print(worksheet.cell_value(0, 0))