我有尝试打开存储在特定位置的Excel文件,并写入一些数据内容,它的应用程序。
这里是我的代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//String inputFile = @"D:\Excel\Input.xlsx";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a New Excel File
// Excel.Workbook oWB = oXL.Workbooks.Add(Type.Missing);
Excel.Workbook oWB = oXL.Workbooks.Open("C:\\Users/diwesh/Downloads/WriteExcel/WriteExcel/WindowsFormsApplication1/bin/Debug/Input.xlsx");
// Excel.Workbook oWB = oXL.Workbooks.Open(@".\Input.xlsx");
Excel._Worksheet oSheet = oWB.ActiveSheet;
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
oSheet.Cells[1, 3] = txt_Name.Text;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = Color.SkyBlue;
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
oSheet.get_Range("A1", "B3").Font.Bold = true;
// String ReportFile = @"D:\Excel\Output.xls";
String ReportFile = @".\Excel\Output.xls";
oWB.SaveAs(ReportFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault,
Type.Missing, Type.Missing,
false,
false,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//MessageBox.Show("Thank you the excel data has been saved");
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
txt_Name.Text = "Diwesh";
}
}
}
故障1:Excel.Workbook oWB = oXL.Workbooks.Open(@".\Input.xlsx");
这不找到“Input.xlsx”,开辟了刚刚申请,除非我给它一个完整路径,如:
Excel.Workbook oWB = oXL.Workbooks.Open("C:\\Users/diwesh/Downloads/WriteExcel/WriteExcel/WindowsFormsApplication1/bin/Debug/Input.xlsx");
问题2:它总是进入异常循环。
请帮忙。
这是形式的样子:
作为一个善意的建议:使用类似EPPLUS的库来读取/写入excel文件。在开发过程中,方式更快,方式更有弹性,更少头痛 – 2014-09-02 06:30:21
@ChristianSauer:感谢您的建议。要保存的数据并不那么庞大。所以我避免使用一个额外的库。这段代码工作得很好,没有任何延迟。我遇到的唯一问题就是列出,如果你可以帮忙的话。 – user3828453 2014-09-02 06:49:30
暂时删除try/catch块,看看你到底在哪一行得到异常。我相信这不是行'oWB = oXL.Workbooks.Open(...' – 2014-09-03 08:08:39