[英]What is the best design pattern to read an excel with multiple sheets
我有一個具有標准格式的Excel工作表,該工作表將包含多個工作表。 我需要閱讀Java中的圖紙並將它們轉換為對象並存儲在數據庫中。 我目前正在使用簡單工廠模式。 我正在讀取工作表名稱,並基於工作表名稱調用相應的轉換器對象。 這是實現這一目標的唯一方法還是有更好的方法。 下面是示例代碼。
FileInputStream fis = new FileInputStream(new File("test.xls"));
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
int numberOfSheets = hssfWorkbook.getNumberOfSheets();
for (int i=0; i<numberOfSheets; i++) {
HSSFSheet sh = hssfWorkbook.getSheetAt(i);
String sname = sh.getSheetName();
switch (sname) {
case "Test" : //go to test convertor;
case "Test1": //go to test1 convertor
}
}
我會選擇strategy design pattern
。
您可以有一個ISheetConverter
和多個實現來定義其自己的轉換邏輯。 它看起來像:
@FunctionalInterface
inferface ISheetConverter {
POJOForSheet convert(SheetStream sheetFromIO);
}
同樣,您現有的工廠類可以基於sh.getSheetName()
返回適當的ISheetConverter
類 sh.getSheetName()
稍后將進行轉換)。
當然,這里的策略模式很合適。
完整的代碼如下(盡管在C#中),但應說明實現方式
class Program
{
private static void Main(string[] args)
{
IStrategyManager manager = new StrategyManager(); // this code is added
FileInputStream fis = new FileInputStream(new File("test.xls"));
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
int numberOfSheets = hssfWorkbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++)
{
HSSFSheet sh = hssfWorkbook.getSheetAt(i);
String sname = sh.getSheetName();
manager.Manage(sname); // this code is added
}
}
}
StrategyManager存儲所有轉換器
interface IStrategyManager
{
void Manage(string sheetName);
}
class StrategyManager : IStrategyManager
{
private Dictionary<string, IConverter> dictionary = new Dictionary<string, IConverter>();
public StrategyManager()
{
// store converter name & its implementation class name which are one and same
dictionary.Add("Test", new Test());
dictionary.Add("Test2", new Test2());
}
public void Manage(string sheetName)
{
dictionary[sheetName].Convert(sheetName); // magic happens here
}
}
各種類型的轉換器實現如下
interface IConverter
{
void Convert(string sheetName);
}
class Test : IConverter
{
public void Convert(string sheetName)
{
/* conversion logic for test converter goes here*/
}
}
class Test2 : IConverter
{
public void Convert(string sheetName)
{
/* conversion logic for test2 converter goes here*/
}
}
@ user3310115,希望能對您有所幫助,如果需要任何說明,請緊緊抓住我。謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.