using NPOI.HSSF.UserModel;
using NPOI.HSSF.Extractor;
using TestCases.HSSF;
// 下面是选择.XLS文件所在地的BUTTON
private void Button_SelcetFile_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "xls files (*.xls)|*.xls|All files (*.*)|*.*"; //只选取xls文件
OFD.RestoreDirectory = true; //还原当前目录
if (OFD.ShowDialog() == DialogResult.OK)
{
textBox_xlsPath.Text = OFD.FileName; //将文件路径放入路径显示文本框
}
}
/// <summary>
/// 读取xls指定页、指定行、指定列的数值
/// </summary>
/// <param name="fileName">文件路径和文件名</param>
/// <param name="sheetNum">页</param>
/// <param name="rowNum">行</param>
/// <param name="colNum">列</param>
/// <returns>返回指定文件、页、行、列的数值</returns>
private string readXls(string fileName, int sheetNum, int rowNum, int colNum)
{
try
{
HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook(fileName);
ExcelExtractor extractor = new ExcelExtractor(workbook);
return extractor.CellValue(sheetNum, rowNum, colNum);
}
catch (System.Exception ex)
{
MessageBox.Show("Error!\n请检查此文件是否已被打开或被其他应用程序占用!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return "";
}
}
/// <summary>
/// 检查相应路径的文件是否存在,你的xls行列异常值的检测也可以丢进来
/// </summary>
/// <returns>返回是否存在的bool值</returns>
private bool checkParams()
{
if (!System.IO.File.Exists(this.textBox_xlsPath.Text))
{
MessageBox.Show("The selected file is not exists, please select again!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
// 读取XLS行列对应值的函数,也可以不用函数,直接把里面的语句放到你程序想读取值的地方即可
private void Read_XLS_Value()
{
string Temp;
Temp = readXls(textBox_xlsPath.Text, 0, 1, 2); //参数分别是:XLS文件地址,sheet页号,行号,列号
//textBox_xlsPath 在上面的函数中被赋值为地址了,页、行、列号起始都是从0开始计数,这里要注意
MessageBox.Show(string.Format(" 让我们看看取到的值是否正确{0}", copy_reduction));
} |