namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Microsoft.Office.Interop.Excel.Application excelApplication = null;
private Workbooks excelWorkBooks = null;
private Workbook excelWorkBook = null;
private Worksheet excelWorkSheet = null;
private Range excelRange = null;//Excel Range Object,多种用途
public int ActiveSheetIndex = 0;
private void Form1_Load(object sender, EventArgs e)
{
excelApplication = null;//Excel Application Object
excelWorkBooks = null;//Workbooks
excelWorkBook = null;//Excel Workbook Object
excelWorkSheet = null;//Excel Worksheet Object
ActiveSheetIndex = 1;
//测试以下的函数是否正确
OpenExcelFile("F:\\ee.xls");
//setOneCellValue(2, 2, "i love u");
//MessageBox.Show("cell:"+getOneCellValue(2,2));
//MessageBox.Show("value:" + getCellsValue(excelWorkSheet.Cells[1,2], excelWorkSheet.Cells[2,3])[0]);
setCellsValue(excelWorkSheet.Cells[2, 2], excelWorkSheet.Cells[3, 3], "same");
SetActiveWorkSheet(1);
System.Data.DataTable dt = new System.Data.DataTable();
dt = getAllCellsValue();
dataGridView1.DataSource = dt;
dt.TableName = "table1";
dt.AcceptChanges();
//MessageBox.Show("value:" + getTotalRowCount().ToString());
//MessageBox.Show("value:" + getTotalColumnCount().ToString());
saveExcel("F:\\save2.xls");
}
public void saveExcel(string excelSaveFileName)
{
if (File.Exists(excelSaveFileName))
{
if (MessageBox.Show(excelSaveFileName + "已存在,需要覆盖吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
File.Delete(excelSaveFileName);
excelWorkSheet.SaveAs(excelSaveFileName, Excel.XlFileFormat.xlTemplate, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
closeApplication();
}
else
{
MessageBox.Show(excelSaveFileName + "已存在,请重新指定文件名字");
}
}
else
{
excelWorkSheet.SaveAs(excelSaveFileName, Excel.XlFileFormat.xlTemplate, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
closeApplication();
}
}
///
/// 以excelOpenFileName为模板新建Excel文件
///
public bool OpenExcelFile(string excelOpenFileName)
{
if (excelApplication != null)
closeApplication();
if (excelOpenFileName == "")
{
throw new Exception("请选择文件!");
}
if (!File.Exists(excelOpenFileName))
{
throw new Exception(excelOpenFileName + "该文件不存在!");
}
try
{
excelApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelWorkBooks = excelApplication.Workbooks;
excelWorkBook = ((Workbook)excelWorkBooks.Open(excelOpenFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex];
excelApplication.Visible = false;
return true;
}
catch (Exception e)
{
closeApplication();
MessageBox.Show("(1)没有安装Excel 2003;(2)或没有安装Excel 2003 .NET 可编程性支持;\n详细信息:"
+ e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
}
///
/// 读取一个Cell的值
///
/// 要读取的Cell的行索引
/// 要读取的Cell的列索引
///
public string getOneCellValue(int CellRowID, int CellColumnID)
{
if (CellRowID <= 0)
{
throw new Exception("行索引超出范围!");
}
string sValue = "";
try
{
sValue = ((Range)excelWorkSheet.Cells[CellRowID, CellColumnID]).Text.ToString();
}
catch (Exception e)
{
closeApplication();
throw new Exception(e.Message);
}
return (sValue);
}
///
/// 读取一个连续区域的Cell的值(矩形区域,包含一行或一列,或多行,多列),返回一个一维字符串数组。
///
/// StartCell是要写入区域的左上角单元格
/// EndCell是要写入区域的右下角单元格
///
public string[] getCellsValue(Object StartCell, Object EndCell)
{
string[] sValue = null;
excelRange = (Range)excelWorkSheet.get_Range(StartCell, EndCell);
sValue = new string[excelRange.Count];
int rowStartIndex = ((Range)excelWorkSheet.get_Range(StartCell, StartCell)).Row; //起始行号
int columnStartIndex = ((Range)excelWorkSheet.get_Range(StartCell, StartCell)).Column; //起始列号
int rowNum = excelRange.Rows.Count; //行数目
int columnNum = excelRange.Columns.Count; //列数目
int index = 0;
for (int i = rowStartIndex; i < rowStartIndex + rowNum; i++)
{
for (int j = columnStartIndex; j < columnNum + columnStartIndex; j++)
{
//读到空值null和读到空串""分别处理
sValue[index] = ((Range)excelWorkSheet.Cells[i, j]).Text.ToString();
index++;
}
}
return (sValue);
}
///
/// 读取所有单元格的数据(矩形区域),返回一个datatable.假设所有单元格靠工作表左上区域。
///
public System.Data.DataTable getAllCellsValue()
{
int columnCount = getTotalColumnCount();
int rowCount = getTotalRowCount();
System.Data.DataTable dt = new System.Data.DataTable();
//设置datatable列的名称
for (int columnID = 1; columnID <= columnCount; columnID++)
{
dt.Columns.Add(((Excel.Range)excelWorkSheet.Cells[1, columnID]).Text.ToString());
}
for (int rowID = 2; rowID <= rowCount; rowID++)
{
DataRow dr = dt.NewRow();
for (int columnID = 1; columnID <= columnCount; columnID++)
{
dr[columnID - 1] = ((Excel.Range)excelWorkSheet.Cells[rowID, columnID]).Text.ToString();
//读到空值null和读到空串""分别处理
}
dt.Rows.Add(dr);
}
return (dt);
}
public int getTotalRowCount()
{//当前活动工作表中有效行数(总行数)
int rowsNumber = 0;
try
{
while (true)
{
if (((Range)excelWorkSheet.Cells[rowsNumber + 1, 1]).Text.ToString().Trim() == "" &&
((Range)excelWorkSheet.Cells[rowsNumber + 2, 1]).Text.ToString().Trim() == "" &&
((Range)excelWorkSheet.Cells[rowsNumber + 3, 1]).Text.ToString().Trim() == "")
break;
rowsNumber++;
}
}
catch
{
return -1;
}
return rowsNumber;
}
///
/// 当前活动工作表中有效列数(总列数)
///
///
public int getTotalColumnCount()
{
int columnNumber = 0;
try
{
while (true)
{
if (((Range)excelWorkSheet.Cells[1, columnNumber + 1]).Text.ToString().Trim() == "" &&
((Range)excelWorkSheet.Cells[1, columnNumber + 2]).Text.ToString().Trim() == "" &&
((Range)excelWorkSheet.Cells[1, columnNumber + 3]).Text.ToString().Trim() == "")
break;
columnNumber++;
}
}
catch
{
return -1;
}
return columnNumber;
}
///
/// 向一个Cell写入数据
///
/// CellRowID是cell的行索引
/// CellColumnID是cell的列索引
///要写入该单元格的数据值
public void setOneCellValue(int CellRowID, int CellColumnID, string Value)
{
try
{
excelRange = (Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
excelRange.Value2 = Value;//Value2?
excelRange = null;
}
catch (Exception e)
{
closeApplication();
throw new Exception(e.Message);
}
}
///
/// 设置活动工作表
///
/// 要设置为活动工作表的索引值
public void SetActiveWorkSheet(int SheetIndex)
{
if (SheetIndex <= 0)
{
throw new Exception("索引超出范围!");
}
try
{
ActiveSheetIndex = SheetIndex;
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex];
}
catch (Exception e)
{
closeApplication();
throw new Exception(e.Message);
}
}
///
/// 向连续区域一次性写入数据;只有在区域连续和写入的值相同的情况下可以使用方法
///
/// StartCell是要写入区域的左上角单元格
/// EndCell是要写入区域的右下角单元格
/// 要写入指定区域所有单元格的数据值
public void setCellsValue(object StartCell, object EndCell, string Value)
{
try
{
excelRange = excelWorkSheet.get_Range(StartCell, EndCell);
excelRange.Value2 = Value;
excelRange = null;
}
catch (Exception e)
{
closeApplication();
throw new Exception(e.Message);
}
}
//关闭application
public void closeApplication()
{
excelApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
excelApplication = null;
GC.Collect();
}
}
}