库需求
需要NPOI库(处理Excel表格库)
可在vs工具菜单栏中的NuGet包管理器中搜索NPOI下载·获得
效果简单预览
读
点击查看代码
private void btnRead_Click_1(object sender, EventArgs e)
{
#region 打开对话框,自定义选择要读取excel表格路径
StringBuilder sbr = new StringBuilder();
OpenFileDialog p = new OpenFileDialog();
p.Filter = "格式|*.xls;*.xlsx";
string pa = "";
if (p.ShowDialog() == DialogResult.OK)
{
pa = p.FileName;
}
#endregion
try //使用try可以获得要打开的excel表是否被占用信息
{
using (FileStream fs = File.OpenRead(pa)) //打开myxls.xls文件,用文件流方式
{
#region 判断Excel版本
IWorkbook wk;
if (pa.IndexOf(".xlsx") > 0)// 2007版本
{ wk = new XSSFWorkbook(fs); }
else if (pa.IndexOf(".xls") > 0) // 2003版本
{ wk = new HSSFWorkbook(fs); }
else
{
wk = null;
}
//把xls文件中的数据写入wk中
#endregion
ISheet sheet = wk.GetSheetAt(0); //读取当前表数据
#region DataGridView 必须要先创建列信息 这里模仿exccel行列的ADCB与123,分别为view的列头和行头
for (int i = 0; i < sheet.GetRow(0).LastCellNum; i++)
{
char o = 'A';
for (char j = 'A'; j < 'Z'; j++)
{
if ((i + 65) == j)
{
o = j;
}
}
dataGridView1.Columns.Add(i.ToString(), o.ToString());//添加列
}
#endregion
#region 将每一个excel的单元格内容写入view表中
for (int j = 0; j <= sheet.LastRowNum; j++) //LastRowNum 是当前表的总行数
{
IRow row = sheet.GetRow(j); //读取当前行数据
if (row != null)
{
string[] str = new string[row.LastCellNum];
for (int k = 0; k < row.LastCellNum; k++) //LastCellNum 是当前行的总列数
{
ICell cell = row.GetCell(k); //当前表行的格列单元
str[k] = cell.ToString();
}
dataGridView1.Rows.Add(str);
dataGridView1.Rows[j].HeaderCell.Value = (j + 1).ToString();//写入view单元格
}
}
#endregion
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
写
点击查看代码
private void btnWrite_Click(object sender, EventArgs e)
{
IWorkbook wb = new HSSFWorkbook();
ISheet sh = wb.CreateSheet("zhiyuan");
#region 将DataGridView数据遍历给Excel,都需要创建行列才能添加数据
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
IRow row1 = sh.CreateRow(i);
for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
{
ICell icell2top = row1.CreateCell(j);
//这里SetCellValue()方法有多个重载,参数是什么类型,写入的数值对应excel的类型,excel数据类型有很多,如字符串、数值等
icell2top.SetCellValue(double.Parse(dataGridView1.Rows[i].Cells[j].Value.ToString()));
}
}
#endregion
#region 自定义保存Excek路径
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "*.xls格式|*.xls|*.xlsx格式|*.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (FileStream stm = File.OpenWrite(saveFileDialog.FileName))
{
wb.Write(stm);
MessageBox.Show("保存成功");
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
#endregion
}