首先确定pc装的excel是什么版本,如果是1997-2003那么导入的dll就是Microsoft Excel 11.0 Object Library,否则会报错,如果是2007或者2010以上的excel,导入的dll就是Microsoft Excel 12.0 Object Library。以下代码可以直接使用,如果pc没有装过excel,那是无法使用的,那些用流文件生成的excel是假的,不建议使用,因为高版本excel(大于2007)打开就会报错格式问题。
using Microsoft.Office.Interop.Excel;
/// <summary>
/// 将制定sheet中的数据导出到datatable中
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
internal System.Data.DataTable ImportExcel(string filePath)
{
DataSet ds=null;
System.Data.DataTable dt=null;
Microsoft.Office.Interop.Excel.Application excel=new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook=null;
Microsoft.Office.Interop.Excel.Worksheet worksheet=null;
Microsoft.Office.Interop.Excel.Sheets sheets=null;
Microsoft.Office.Interop.Excel.Range range=null;
object missing=System.Reflection.Missing.Value;
try
{
if (excel == null)
{
return null;
}
//打开Excel文件
workbook = excel.Workbooks.Open(
filePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//获取所有的sheet表
sheets = workbook.Worksheets;
ds = new DataSet();
for (int i = 1; i <= sheets.Count; i++)
{
//获取第一个表
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(i);
int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;
int rowIndex = 1;
int colIndex = 1;
DataColumn dc;
dt = new System.Data.DataTable();
dt.TableName = "table" + i.ToString();
//读取列名
for (int j = 0; j < colCount; j++)
{
range = worksheet.Cells[rowIndex, colIndex + j];
dc = new DataColumn();
dc.DataType = Type.GetType("System.String");
dc.ColumnName = range.Text.ToString().Trim();
//添加列
dt.Columns.Add(dc);
}
//读取行数据
for (int k = 1; k < rowCount; k++)
{
DataRow dr = dt.NewRow();
for (int l = 0; l < colCount; l++)
{
range = worksheet.Cells[rowIndex + k, colIndex + l];
dr[l] = range.Text.ToString();
}
//dt.Tables.Add(dr);
dt.Rows.Add(dr);
}
}
}
catch (Exception ex)
{
throw;
}
finally
{
workbook.Close();
excel.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
worksheet=null;
workbook=null;
excel=null;
GC.Collect();
}
// return ds;
return dt;
}
/// <summary>
/// 将datatable导出到excel
/// </summary>
/// <param name="tb1"></param>
/// <returns></returns>
internal bool ExportToExecl(System.Data.DataTable tb1)
{
System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "xlsx";
sfd.Filter = "Excel文件(*.xlsx)|*.xlsx";
if (sfd.ShowDialog() != DialogResult.OK)
{
// DoExport(dgv, sfd.FileName);
return false ;
}
// ExportForDataGridview(dt, sfd.FileName, false);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
if (app == null)
{
return false;
}
app.Visible = false;//不打开excel
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
return false;
}
string sLen = "";
//取得最后一列列名
char H = (char)(64 + tb1.Columns.Count / 26);
char L = (char)(64 + tb1.Columns.Count % 26);
if ( tb1.Columns.Count < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
}
//标题
string sTmp = sLen + "1";
Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[ tb1.Columns.Count ];
for (int i = 0; i < tb1.Columns.Count ; i++)//生成列名
{
asCaption[i] = tb1.Columns[i].ColumnName;
}
ranCaption.Value2 = asCaption;
//数据
object[] obj = new object[tb1.Rows.Count];
for (int r = 0; r < tb1.Rows.Count ; r++)//轮询行
{
if (r == 18)
{ }
for (int l = 0; l <tb1.Columns.Count; l++)//填充列的值
{
if( tb1.Columns[l].DataType == typeof(DateTime))
{
obj[l] = tb1.Rows[r][l].ToString();
}
else
{
obj[l] = tb1.Rows[r][l];
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Range ran = worksheet.get_Range(cell1, cell2);
ran.Value2 = obj;
}
//保存
if (!File.Exists( sfd.FileName))
{
FileStream fs = File.Create( sfd.FileName);//创建文件
fs.Close();
}
workbook.SaveCopyAs( sfd.FileName);
workbook.Saved = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
finally
{
//关闭
app.UserControl = false;
app.Quit();
}
return true;
}