选择文件
public static string OpenExcel()
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
if (fileDialog.ShowDialog() == DialogResult.OK)
{
return fileDialog.FileName;//返回文件的完整路径
}
else
{
return null;
}
}
导入按钮
private void button1_Click(object sender, EventArgs e)//导入按钮
{
string filePath = OpenExcel();
if (!string.IsNullOrEmpty(filePath))
{
IWorkbook workbook = spreadsheetControl1.Document;
workbook.LoadDocument(filePath);
}
}
保存按钮
private void button2_Click(object sender, EventArgs e)//保存按钮
{
try
{
spreadsheetControl1.SaveDocument();
}
catch (Exception ExError)
{
MessageBox.Show("该文件正被别的地方占用");
ExError.ToString();
}
}
另存为按钮
private void button3_Click(object sender, EventArgs e)//另存为按钮
{
//获取要保存的文件路径
string filePath = SaveExcel();
//如果不为空
if (!string.IsNullOrEmpty(filePath))
{
try
{
//获取预览的excel对象 Document提供对控件中加载的工作簿的访问
IWorkbook workbook = spreadsheetControl1.Document;
//根据选择的路径保存excel
workbook.SaveDocument(filePath);
//弹窗提示
MessageBox.Show("保存成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
保存
public static string SaveExcel()
{
string filename = "";
SaveFileDialog saveDialog = new SaveFileDialog();
//设置默认文件扩展名。
saveDialog.DefaultExt = "xls";
//设置当前文件名筛选器字符串,该字符串决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容。
saveDialog.Filter = "Excel文件|*.xls";
// 用默认的所有者运行通用对话框。
saveDialog.ShowDialog();
//如果修改了文件名,用对话框中的文件名名重新赋值
filename = saveDialog.FileName;
//被点了取消
if (filename.IndexOf(":") < 0) return null;
else
{
//获取文件对话框中选定的文件名的字符串
return saveDialog.FileName.ToString();
}
}
打印按钮
private void button4_Click(object sender, EventArgs e)//打印按钮
{
this.spreadsheetControl1.ShowPrintPreview();
}