C# 작업 Excel 테이블
3904 단어 Excel
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using ExcelTest.Properties;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelTest
{
public partial class Form1 : Form
{
public static string StrCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.xls;Extended Properties=Excel 8.0";
public static DataSet Ds;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,EventArgs e)
{
}
private void button1_Click(object sender,EventArgs e)
{
var fileName = Application.StartupPath + "\\1.xls";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
var excel = new Excel.ApplicationClass
{Visible = false, DisplayAlerts = false, AlertBeforeOverwriting = false};
try
{
var book = excel.Workbooks.Add(true);
var sheet = book.Worksheets[1] as Excel.Worksheet;
if (sheet != null) sheet.Cells[1,1] = "123";
book.Save();
book.Close(Type.Missing, Type.Missing, Type.Missing);
// excel
excel.Save(fileName);
excel.SaveWorkspace(fileName);
}
catch (Exception)
{
}
CloseExcelApp(excel);
}
private void button2_Click(object sender,EventArgs e)
{
var fileName = Application.StartupPath + "\\1.xls";
if (!File.Exists(fileName))
{
MessageBox.Show(Resources.Form1_button2_Click_ _); return; ;
}
var excel = new Excel.ApplicationClass
{Visible = false,DisplayAlerts = false,AlertBeforeOverwriting = false};
try
{
var workbooks = excel.Workbooks;
workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
var book = workbooks.get_Item(1);
var sheet = book.Worksheets[1] as Excel.Worksheet;
sheet.Cells[1,1] = "234";
sheet = null;
book.Save();
// excel
excel.Save(fileName);
excel.SaveWorkspace(fileName);
}
catch (Exception)
{
}
CloseExcelApp(excel);
}
private void button3_Click(object sender,EventArgs e)
{
var conn = new OleDbConnection(StrCon);
const string sql = "select * from [Sheet1$]";
//const string sql = "delete from [Sheet1$]";
conn.Open();
var myCommand = new OleDbDataAdapter(sql,StrCon);
Ds = new DataSet();
myCommand.Fill(Ds,"[Sheet1$]");
conn.Close();
dataGridView1.DataSource = Ds.Tables[0];
}
private void button4_Click(object sender, EventArgs e)
{
var excel = new Excel.ApplicationClass {Visible = false};
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
}
void CloseExcelApp(Excel.ApplicationClass app)
{
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Excel Grep toolExcel Grep tool ■히나가타 ■ 시트 구성 ExcelGrep.cls...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.