同时读取多个线程中的单元格值
Contents
[
Hide
]
需要同时在多个线程中读取单元格值是一个常见的需求。本文解释了如何使用Aspose.Cells来实现这一目的。
为了在多个线程中同时读取单元格值,请将Cells.setMultiThreadReading(boolean)设置为true。否则,可能会得到错误的单元格值。
以下代码:
- 创建一个工作簿。
- 添加一个工作表。
- 用字符串值填充工作表。
- 然后创建两个同时从随机单元格中读取值的线程。 如果读取的值是正确的,则不会发生任何事情。如果读取的值不正确,则会显示一条消息。
如果您注释掉这一行:
testWorkbook.getWorksheets().get(0).getCells().setMultiThreadReading(true);
那么将显示以下消息:
if (s !== "R" + row + "C" + col)
{
console.log("This message box will show up when cells read values are incorrect.");
}
否则,程序将在不显示任何消息的情况下运行,这意味着从单元格中读取的所有值都是正确的。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
const dataDir = path.join(__dirname, "data"); | |
let testWorkbook; | |
const threadLoop = () => { | |
const random = Math.random; | |
while (true) { | |
try { | |
const row = Math.floor(random() * 10000); | |
const col = Math.floor(random() * 100); | |
const s = testWorkbook.getWorksheets().get(0).getCells().get(row, col).getStringValue(); | |
if (s !== "R" + row + "C" + col) { | |
console.log("This message will show up when cells read values are incorrect."); | |
} | |
} catch (e) {} | |
} | |
}; | |
const testMultiThreadingRead = () => { | |
testWorkbook = new AsposeCells.Workbook(); | |
testWorkbook.getWorksheets().clear(); | |
testWorkbook.getWorksheets().add("Sheet1"); | |
for (let row = 0; row < 10000; row++) | |
for (let col = 0; col < 100; col++) | |
testWorkbook.getWorksheets().get(0).getCells().get(row, col).setValue("R" + row + "C" + col); | |
// Uncommenting this line will enable multi-threaded reading | |
//testWorkbook.getWorksheets().get(0).getCells().setMultiThreadReading(true); | |
const myThread1 = setInterval(threadLoop, 0); | |
const myThread2 = setInterval(threadLoop, 0); | |
setTimeout(() => { | |
clearInterval(myThread1); | |
clearInterval(myThread2); | |
}, 5 * 1000); | |
}; | |
testMultiThreadingRead(); |