string
saveFileName =
""
;
saveFileDialog1.InitialDirectory = Application.StartupPath +
"\\"
;
//默认路径为D://
saveFileDialog1.FilterIndex = 1;
//默认值为第一个
saveFileDialog1.RestoreDirectory =
true
;
//重新定位保存路径
saveFileDialog1.Title =
"导出Excel文件到"
;
saveFileDialog1.Filter =
"xls files (*.xls)|*.xls|xlsx files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
;
saveFileDialog1.ShowDialog();
saveFileName = saveFileDialog1.FileName;
if
(saveFileName.IndexOf(
":"
) < 0)
return
;
if
(File.Exists(saveFileName))
File.Delete(saveFileName);
Excel.Application xlApp =
new
Excel.Application();
if
(xlApp ==
null
)
{
MessageBox.Show(
"无法创建Excel对象,可能您的机器未安装Excel"
);
return
;
}
Excel.Workbooks wbooks = xlApp.Workbooks;
Excel.Workbook wbook = wbooks.Add(
true
);
Excel.Worksheet worksheet = (Excel.Worksheet)wbook.Worksheets[1];
xlApp.Visible =
false
;
worksheet.Cells[1, 1] =
"产品名称"
;
//第一行,第一列
worksheet.Cells[1, 2] =
"库存数量"
;
//第一行,第二列
worksheet.Cells[1, 3] =
"借出数量"
;
worksheet.Cells[1, 4] =
"库位"
;
//程序里面产品名称下面有很多产品,所以我这边是一个for循环。你直接改为 worksheet.Cells[a, b]=""
for
(
int
i = 0; i < listView1.Items.Count; i++)
{
for
(
int
j = 0; j <= 2; j++)
{
worksheet.Cells[2 + i, j+1] = listView1.Items[i].SubItems[j].Text;
((Excel.Range)worksheet.Cells[2 + i, j+1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
}
}
object
missing = System.Reflection.Missing.Value;
try
{
wbook.Saved =
true
;
wbook.SaveAs(saveFileName, Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
false
,
false
, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
}
catch
(Exception e1)
{
MessageBox.Show(
"导出文件时出错,文件可能正被打开!\n"
+ e1.Message);
}
finally
{
xlApp.Quit();
System.GC.Collect();
}
MessageBox.Show(
"导出成功!"
);