C #에서 Excel 파일을 여는 방법은 무엇입니까?
일부 VBA 코드를 C # 으로 변환하려고합니다 . 저는 C #을 처음 사용합니다. 현재 폴더에서 Excel 파일을 열려고 시도하고 있는데 파일이 없으면 새로 만듭니다. 다음과 같은 것을 시도하고 있습니다. 어떻게 작동시킬 수 있습니까?
Excel.Application objexcel;
Excel.Workbook wbexcel;
bool wbexists;
Excel.Worksheet objsht;
Excel.Range objrange;
objexcel = new Excel.Application();
if (Directory("C:\\csharp\\error report1.xls") = "")
{
wbexcel.NewSheet();
}
else
{
wbexcel.Open("C:\\csharp\\error report1.xls");
objsht = ("sheet1");
}
objsht.Activate();
Microsoft VSTO (Visual Studio Tools for Office)를 설치해야합니다.
VSTO는 워크로드> 웹 및 클라우드> Office / SharePoint 개발 아래의 Visual Studio 설치 관리자에서 선택할 수 있습니다.
그런 다음 공통 .NET 프로젝트를 만들고 Microsoft.Office.Interop.Excel
'참조 추가 ...> 어셈블리'대화 상자 를 통해 참조를 추가합니다 .
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value
불필요한 매개 변수 교체를위한 특수 리플렉션 구조체입니다.
최신 버전에서 필요한 어셈블리 참조는 Microsoft Excel 16.0 Object Library
. 최신 버전이 설치되어 있지 않은 경우 Microsoft Excel 15.0 Object Library
또는 이전 버전 이있을 수 있지만 포함하는 프로세스는 동일합니다.
FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
System.Diagnostics.Process.Start(@"C:\test\report.xlsx");
}
else
{
//file doesn't exist
}
private void btnChoose2_Click(object sender, EventArgs e)
{
OpenFileDialog openfileDialog1 = new OpenFileDialog();
if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.btnChoose2.Text = openfileDialog1.FileName;
String filename = DialogResult.ToString();
var excelApp = new Excel.Application();
excelApp.Visible = true;
excelApp.Workbooks.Open(btnChoose2.Text);
}
}
Excel 파일 열기
System.Diagnostics.Process.Start(@"c:\document.xls");
이렇게 열어야합니다
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
출처 : http://csharp.net-informations.com/excel/csharp-open-excel.htm
Ruden
수입품
using Excel= Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
다음은 C #을 사용하여 Excel 시트를 여는 코드입니다.
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
wbv.Close(true, Type.Missing, Type.Missing);
excel.Quit();
다음은 C # https://www.youtube.com/watch?v=O5Dnv0tfGv4를 사용하여 Excel 워크 시트를 여는 방법에 대한 비디오 메이트입니다.
파일을 열려면 다음을 시도하십시오.
objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
어리석은 것처럼 보이는 '누락 된'주장을 제공해야합니다. VB.Net에서 동일한 코드를 작성했다면 필요하지 않았을 것이지만 C #에서는 이러한 코드를 피할 수 없습니다.
잘못된 점이나 실행할 때 실패한 점을 말하면 도움이 더 쉽습니다.
But from a quick glance you've confused a few things.
The following doesn't work because of a couple of issues.
if (Directory("C:\\csharp\\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
What you should do (for this line at least) is the following
FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
Microsoft.Office.Interop.Excel.Application excapp;
excapp = new Microsoft.Office.Interop.Excel.Application();
object misval=System.Reflection.Missing.Value;
Workbook wrkbuk = new Workbook();
Worksheet wrksht = new Worksheet();
wrkbuk = excapp.Workbooks._Open(@"C:\Users\...\..._template_v1.0.xlsx", misval, misval,
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);
wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);
Is this a commercial application or some hobbyist / open source software?
내 경험상 모든 무료 .NET Excel 처리 대안에는 여러 가지 이유로 심각한 문제가 있기 때문에 이것을 묻습니다. 취미 생활의 경우 일반적으로 jExcelApi를 Java에서 C #으로 포팅하고 사용합니다.
그러나 이것이 상용 응용 프로그램 인 경우 Aspose.Cells 와 같은 타사 라이브러리를 구입하는 것이 좋습니다 . 저를 믿으십시오. 많은 시간을 절약하고 시간이 무료가 아니므로 그만한 가치가 있습니다.
코드 :
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled=false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excell File |*.xlsx;*,xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
string extn = Path.GetExtension(ofd.FileName);
if (extn.Equals(".xls") || extn.Equals(".xlsx"))
{
filename = ofd.FileName;
if (filename != "")
{
try
{
string excelfilename = Path.GetFileName(filename);
}
catch (Exception ew)
{
MessageBox.Show("Errror:" + ew.ToString());
}
}
}
}
C # 응용 프로그램 내에서 Excel 파일을 편집하기 위해 최근에 NPOI를 사용하기 시작했습니다 . 나는 그것에 매우 만족합니다.
참고 URL : https://stackoverflow.com/questions/464902/how-to-open-an-excel-file-in-c
'Program Tip' 카테고리의 다른 글
양식 제출 전 Jquery 함수 (0) | 2020.12.03 |
---|---|
ansible : 여러 명령을 전달하는 방법 (0) | 2020.12.03 |
Maven-빌드 테스트 클래스 건너 뛰기 (0) | 2020.12.03 |
요소에서 두 번째 클래스 이름을 얻는 방법은 무엇입니까? (0) | 2020.12.03 |
노드가 n 개인 유 방향 그래프에서 최대 간선 수는 얼마입니까? (0) | 2020.12.03 |