初步爬取到需要的數據之後,需要將數據存儲到外部文件中以方便數據處理。本文中採用Excel存儲爬取到的數據內容。與本次設計的數據爬取採用C#中的DataGrid進行顯示,爬取指定基金號碼的歷史基金數據,並將其保存於軟件所在根目錄。軟件見鏈接。
- 使用Excel之前,需要加載Microsoft.Office.Interop.Excel
- 使用Excel的步驟大概分爲以下步驟:
- 加載指定路徑文件,本文以年月日進行命名
- 當工作簿存在時,加載。否則新建工作簿
- 工作頁以基金編碼命名。遍歷工作簿中的工作頁,當不存在爬取基金時,新建工作頁
- 將獲得的數據寫入工作頁,並存儲
- 關閉Excel線程
- 以下代碼未保存數據核心代碼
private void SaveData()
{
Excel.Application application = new Excel.Application();
string path = System.IO.Directory.GetCurrentDirectory();
path = System.IO.Path.Combine(path, DateTime.Now.ToString("yy-MM-dd") + ".xlsx");
Excel.Workbook wb = null;
try
{
if (System.IO.File.Exists(path))
{
wb = application.Workbooks.Open(path);
}
else
{
wb = application.Workbooks.Add();
}
int wsCnt = wb.Worksheets.Count;
Excel.Worksheet ws = null;
string code = string.Empty;
Dispatcher?.Invoke(() =>
{
code = (textBoxCode.Text);
});
for (int i = 0; i < wsCnt; i++)
{
Excel.Worksheet worksheet = wb.Worksheets[i + 1];
if(!string.IsNullOrEmpty(worksheet.Name) &&
worksheet.Name.Equals(code))
{
ws = wb.Worksheets[i + 1];
}
}
if (ws == null)
{
wb.Worksheets.Add();
ws = wb.Worksheets[1];
ws.Name = code;
}
int rIdx = _dt.Rows.Count;
int cIdx = _dt.Columns.Count;
for(int i = 0; i < rIdx; i++)
{
for(int j = 0; j < cIdx; j++)
{
ws.Cells[i + 1, j + 1] = _dt.Rows[i][j];
}
}
if (System.IO.File.Exists(path))
wb.Save();
else
wb.SaveAs(path);
Dispatcher?.Invoke(() => { MessageBox.Show(this, "數據保存完畢"); });
}
catch (Exception exc)
{
Dispatcher?.Invoke(() => { MessageBox.Show(this, exc.Message); });
}
finally
{
ClosePro(path, application, wb);
}
}
- 以下爲釋放Excel線程代碼。該代碼在網絡上很容易搜到
public void ClosePro(string excelPath, Excel.Application excel, Excel.Workbook wb)
{
Process[] localByNameApp = Process.GetProcessesByName(excelPath);//獲取程序名的所有進程
if (localByNameApp.Length > 0)
{
foreach (var app in localByNameApp)
{
if (!app.HasExited)
{
#region
////設置禁止彈出保存和覆蓋的詢問提示框
//excel.DisplayAlerts = false;
//excel.AlertBeforeOverwriting = false;
////保存工作簿
//excel.Application.Workbooks.Add(true).Save();
////保存excel文件
//excel.Save("D:" + "\\test.xls");
////確保Excel進程關閉
//excel.Quit();
//excel = null;
#endregion
app.Kill();//關閉進程
}
}
}
if (wb != null)
wb.Close(true, Type.Missing, Type.Missing);
excel.Quit();
// 安全回收進程
System.GC.GetGeneration(excel);
}
- 軟件運行效果圖