我尝试导入具有多个工作表的Excel文件,我有选择特定工作表的代码。所选表格成功导入后,将提示如下的保存对话框。那么,如何跳过保存过程?
选择文件的代码
void ChooseFile()
{
OFD1.Title = "Get Excel File";
OFD1.FileName = "";
OFD1.Filter = "Excel File|*.xlsx;*.xls";
if(OFD1.ShowDialog() == DialogResult.OK)
{
FileName = OFD1.FileName;
app = new Excel.Application();
workbook = app.Workbooks.Open(FileName);
if(FileName.Trim() != "")
if(workbook.Sheets.Count == 1)
ExcelToGrid();
else
ChooseSheet();
}
}
选择工作表的代码
public void ChooseSheet()
{
for(int SheetNo = 1; SheetNo <= workbook.Sheets.Count; SheetNo++)
cboSheet.Items.Add("Sheet" + SheetNo);
}
导入Excel的代码
public void ExcelToGrid(string SheetNo)
{
app = new Excel.Application();
workbook = app.Workbooks.Open(FileName);
worksheet = workbook.Worksheets[SheetNo];
dgvAddByGroup.Rows.Clear();
dgvAddByGroup.Columns.Clear();
dgvAddByGroup.Columns.Add("dgvSelect", "Select");
int RowNo, ColNo, RowCounter = 0, ColCounter = 0, CellCounter = 0;
for(ColNo = 1; ColNo <= worksheet.Columns.Count; ColNo++)
if(!string.IsNullOrEmpty(Convert.ToString(worksheet.Cells["1", ColNo].value)))
{
dgvAddByGroup.Columns.Add("dgv" + Convert.ToString(worksheet.Cells["1", ColNo].value), Convert.ToString(worksheet.Cells["1", ColNo].value));
ColCounter = 0;
}
else
if(ColCounter == 0)
{
dgvAddByGroup.Columns.Add("", "");
ColCounter = 1;
}
else if(ColCounter == 1)
{
dgvAddByGroup.Columns.RemoveAt(ColNo - 2);
ColCounter = 0;
break;
}
for(RowNo = 1; RowNo <= worksheet.Rows.Count; RowNo++)
{
CellCounter = 0;
dgvAddByGroup.Rows.Add();
dgvAddByGroup.Rows[RowNo - 1].Cells[0].Value = false;
for(ColNo = 1; ColNo <= dgvAddByGroup.Columns.Count; ColNo++)
{
if(!string.IsNullOrEmpty(Convert.ToString(worksheet.Cells[RowNo, ColNo].value)))
{
dgvAddByGroup.Rows[RowNo - 1].Cells[ColNo - 1].Value = Convert.ToString(worksheet.Cells[RowNo, ColNo].value);
CellCounter += 1;
}
else if(string.IsNullOrEmpty(Convert.ToString(worksheet.Cells[RowNo, ColNo].value)))
CellCounter += 0;
}
if(CellCounter == 0)
{
if(RowCounter == 0)
RowCounter = 1;
else if(RowCounter == 1)
{
dgvAddByGroup.Rows.RemoveAt(RowNo - 1);
dgvAddByGroup.Rows.RemoveAt(RowNo - 2);
RowCounter = 0;
break;
}
}
else
{
RowCounter = 0;
}
}
workbook.Close();
app.Quit();
}
Excel图片:
结果图片: