使用NPOI解析excel內容匯入postgres資料庫
阿新 • • 發佈:2019-01-22
一、使用工具NPOI
2.引用dosnet4中的dll,在程式中
using NPOI.SS.UserModel
using NPOI.XSSF.UserModel//這是2007以後版本的office需要引用的
3.使用wpf程式測試excel解析。
前臺xmal:
<Grid> <Button Content="讀取XLS檔案" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="btnInstall" VerticalAlignment="Top" Width="75" Click="btnInstall_Click" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="174,12,0,0" Name="lblLog" Text="" VerticalAlignment="Top" Width="317" /> </Grid>
後臺xmal.cs
StringBuilder sbr = new StringBuilder();//字串操作的類 using (FileStream fs = File.OpenRead(@"c:/myxls.xls")) //開啟myxls.xls檔案 { XSSFWorkbook wk = new XSSFWorkbook(fs);//把xls檔案中資料寫入wk中 for (int i = 0; i < 1; i++)//NumberOfSheets是myxls.xls中sheet表數wk.NumberOfSheets { ISheet sheet = wk.GetSheetAt(i);//讀取當前sheet表的資料 for (int j = 1; j <= sheet.LastRowNum; j++)//LastRowNum是當前表的行數 { IRow row = sheet.GetRow(j);//讀取當前行的資料 if (row != null) { //取各列 for (int n = 0; n <= row.LastCellNum; n++) { ICell cell = row.GetCell(n);//d列的當前cell if (cell != null) { sbr.Append(cell.ToString());//將獲取的表格資料轉換為字串型別 } if (n == row.LastCellNum) { lblLog.Text = "資料讀取成功"; } } } } } }
4.對讀取的內容進行字串解析
string[] a=null;
a=cellstring.Split('\n');
//或者 cellstring.Split(new char[2]{'\r','\n'})
5.建資料庫表結構,生成相關Model6.寫介面和insert方法
7.呼叫business介面,最後調整下生成資料庫的結構