教程不完整,不如不写。网搜了一大片东拼西凑才搞完,无奈嘞。
插入excel文件,网上两大流派:
using Microsoft.Office.Interop.Excel;
using NPOI;
本教程使用的是上者,喜欢后者的不用看下去了。
再者,插入excel又分为两种情况,已有excel文件以及需要新建excel文件。单独写了个类,小功能所以没怎么调整,只是微调,杂乱的注释和不明所以得代码请忽略。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;
using System.IO;
using Microsoft.Office.Interop.Excel;
using Excel=Microsoft.Office.Interop.Excel;
using crl = System.Runtime.InteropServices.Marshal; //ReleaseComObject(Object O)
namespace Rice_Color_Extraction
{
public class ExportDGVToExcel
{
private const int OLDOFFICEVESION = -4143;
private const int NEWOFFICEVESION = 56;
/// <summary>
/// DataGridView导出Excel
/// </summary>
/// <param name="strCaption">Excel文件中的标题</param>
/// <param name="myDGV">DataGridView 控件</param>
/// <returns>0:成功;1:DataGridView中无记录;2:Excel无法启动;100:Cancel;9999:异常错误</returns>
public int ExportExcel(string strCaption, DataGridView myDGV, SaveFileDialog saveFileDialog)
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
//saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog.FileName == "")
{
MessageBox.Show("请输入保存文件名!");
saveFileDialog.ShowDialog();
}
// 列索引,行索引,总列数,总行数
int ColIndex = 0, RowIndex = 0;
int ColCount = myDGV.ColumnCount, RowCount = myDGV.RowCount;
if (myDGV.RowCount == 0)
{
return 1;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application xlApp = new ApplicationClass();
if (xlApp == null)
{
return 2;
}
try
{
// 创建Excel工作薄
Workbook xlBook = xlApp.Workbooks.Add(true);
Worksheet xlSheet = (Worksheet)xlBook.Worksheets[1];