初步爬取到需要的数据之后,需要将数据存储到外部文件中以方便数据处理。本文中采用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);
}
- 软件运行效果图