这应该是一个从2个excel文件读取的程序,将数据存储在两个数组中,并允许用户通过文本框搜索特定的zip /位置,并在搜索框中输入时提示该地点/ s通过标签与之相关,反之亦然。
我的问题是文件需要花费太多时间才能变红。我愿意接受如何缩短阅读时间的建议。
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel ;
namespace ExcelDateilesen_1
{
public partial class Form1 : Form
{
string[] zip = new string[3000];
string[] place = new string[3000];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Excel.Application objExcel = new Excel.Application();
Excel.Workbook objWorkbook = objExcel.Workbooks.Open
(@"C:\Users\ggr\Documents\plz.xlsx");
Excel.Worksheet objWorksheet = objWorkbook.Worksheets["Tabelle1"];
Excel.Range objCell;
int i = 1;
do
{
objCell = objWorksheet.Cells[i, 1];
if (objCell.Value == null) break;
if (objCell.Value is string)
{
zip[i - 1] = objCell.Value;
}
i++;
} while (true);
objWorkbook.Close();
objExcel.Quit();
Excel.Application objExcel1 = new Excel.Application();
Excel.Workbook objWorkbook1 = objExcel1.Workbooks.Open
(@"C:\Users\ggr\Documents\ort.xlsx");
Excel.Worksheet objWorksheet1 = objWorkbook1.Worksheets["Tabelle1"];
Excel.Range objCell1;
int j = 1;
do
{
objCell1 = objWorksheet1.Cells[j, 1];
if (objCell1.Value == null) break;
if (objCell1.Value is string)
{
place[j - 1] = objCell1.Value;
}
j++;
} while (true);
objWorkbook1.Close();
objExcel1.Quit();
}
}
}
答案 0 :(得分:0)
使用您的代码读取包含3000行数据的每个Excel文件大约需要20秒。我创建了一个方法(ReadSheet),而不是循环遍历Excel文件并查找空单元格,该方法将获取Excel工作表并返回第一列数据的字符串数组3000行。我使用对象Array
来获取所有单元格值,然后将其强制转换为字符串数组。阅读速度要快得多。不幸的是,我无法利用worksheet.UsedRange
函数来获取所有行,无论多少行,因为它一直给我错误的数字。我将不得不研究这个问题。希望这会有所帮助。
编辑:更改为UsedRange以获取所有单元格。我遇到的问题是我使用的excel表。
public partial class Form1 : Form
{
string[] zip;
string[] place;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Excel.Application objExcel = new Excel.Application();
Excel.Workbook objWorkbook = objExcel.Workbooks.Open(@"C:\Users\John\Desktop\cs\TestExcel2_3000.xlsx");
Excel.Worksheet objWorksheet = objWorkbook.Worksheets["Tabelle1"];
zip = ReadSheet(objWorksheet);
objWorkbook.Close();
Excel.Workbook objWorkbook1 = objExcel.Workbooks.Open(@"C:\Users\John\Desktop\cs\TestExcel3_3000.xlsx");
Excel.Worksheet objWorksheet1 = objWorkbook1.Worksheets["Tabelle1"];
place = ReadSheet(objWorksheet1);
objWorkbook1.Close();
objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkbook1);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel);
}
private string[] ReadSheet(Excel.Worksheet inSheet)
{
Excel.Range targetCells = inSheet.UsedRange;
//Excel.Range targetCells = inSheet.Range["A1:A3000"];
Array allValues = (Array)targetCells.Cells.Value;
return allValues.Cast<string>().ToArray();
}
}